angular - 想要监视在 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 函数,所以请给我一点建议,我该怎么做?
解决方案
这取决于。
如果里面的逻辑有一些后果,我的被测单元必须对其负责,那么我会通过调用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();
});
推荐阅读
- python - POST 请求适用于 POSTMAN,但不适用于 Python 和 cURL
- javascript - 替换 javascript nashorn:mozilla_compat.js 在 ant 脚本中使用
- php - 如何使用 Supervisor 在 AWS Lightsail 实例上运行 Websocket 服务器
- sql - 带有输入参数的查询不会编译为视图
- c# - 如何从数据库中读取位值并将该值设置为布尔会话变量(如果不为空)
- chat - 关于 Angular 8 sendbird 聊天的建议
- web-scraping - Scrapy init 返回一个 None
- facebook - Facebook 和公共页面内容
- python - 将数据框的默认索引更改为列
- c++ - 使用 dtostrf 将多个浮点值转换为字符串