Want to spy on method which initialize in onInit method

Viewed 1426

I want to test my customForm component,which uses component from another library.Firstly i want to test that my component initialized nested library component. Let me show example:

 @Component({
  selector: 'iris-field-editor',
  template `<span>SomeMarkup</span><editorLibrary [init]="init">` ,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => IrisFieldEditorComponent),
      multi: true
    }
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class IrisFieldEditorComponent implements OnInit, 
ControlValueAccessor {

  constructor() {
  }

  ngOnInit() {
    this.init = {
      height: '20px',
      autoresize_min_height: '20px',
      autoresize_max_height: '600px',
      someOtherSettings,
      setup: (editor) => {
        editor.on('focus',  (e) => {
           //dom manipulation logic
        });

        editor.on('blur', (e) => {
          //dom manipulation logic
        });
      }
    }
  }
}

I tried to use spyOn(component.init,'setup'); expect(component.init.setup).toHaveBeenCalled() but got error: <spyOn> : setup() method does not exist.How can i test method which initialize later in ngOnInit?

Also i wanted to test editor.on functions inside setup function,so mb little advice how can i do this?

1 Answers

It depends.

If the logic inside ngOnInit has some consequences that my unit under test has to hold it accountable, then I would arrange my test case by calling ngOnInit before act. But this, of course, will make them dependent. Any changes in ngOnInit will affect this unit under test too.

So, I hope your unit under test does not care what ngOnInit does, but only interact with this.init.setup. In this case, I would create a spied object through jasmine.createSpyObj or simply mock this.init.setup and spy on it.

it('call setup', () => {
  // with mock function then spy on
  comp.init = { setup: () => {} };
  spyOn(comp.init, 'setup');

  comp.myUnitUnderTest(); // or some kind of actions

  expect(comp.init.setup).toHaveBeenCalled();
});
Related