要监视在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函数,所以mb小建议我该怎么做?

这取决于情况。

如果ngOnInit内部的逻辑导致我的测试单元必须对其负责,那么我会在行动之前调用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();
});

最新更新