gpt4 book ai didi

angular - 想监视在 onInit 方法中初始化的方法

转载 作者:行者123 更新时间:2023-12-04 17:42:10 25 4
gpt4 key购买 nike

我想测试我的 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 中初始化的方法?

我还想在设置函数中测试 editor.on 函数,所以请给我一些建议,我该怎么做?

最佳答案

视情况而定。

如果 ngOnInit 中的逻辑导致我的被测单元必须对其负责,那么我会在操作前调用 ngOnInit 来安排我的测试用例。但这当然会使他们产生依赖性。 ngOnInit 中的任何更改也会影响这个被测单元。

所以,我希望您的测试单元不关心 ngOnInit 做了什么,而只与 this.init.setup 交互。在这种情况下,我会通过 jasmine.createSpyObj 创建一个 spy 对象。或者简单地模拟 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();
});

关于angular - 想监视在 onInit 方法中初始化的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com