首页 > 解决方案 > 想要监视在 onInit 方法中初始化的方法

问题描述

我想测试我的 customForm 组件,它使用来自另一个库的组件。首先我想测试我的组件是否初始化了嵌套库组件。让我举个例子:

 @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
        });
      }
    }
  }
}

我尝试使用 spyOn(component.init,'setup'); expect(component.init.setup).toHaveBeenCalled()但得到了 error: <spyOn> : setup() method does not exist。我如何测试稍后在 ngOnInit 中初始化的方法?

我还想测试 setup 函数中的 editor.on 函数,所以请给我一点建议,我该怎么做?

标签: angularunit-testingjasmine

解决方案


这取决于。

如果里面的逻辑有一些后果,我的被测单元必须对其负责,那么我会通过调用before actngOnInit来安排我的测试用例。ngOnInit但这当然会使他们产生依赖。任何更改ngOnInit都会影响这个被测单元。

所以,我希望你的被测单元不关心做什么ngOnInit,而只关心与this.init.setup. 在这种情况下,我会创建一个间谍对象,jasmine.createSpyObj或者只是模拟this.init.setup和监视它。

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();
});

推荐阅读