【发布时间】:2021-06-14 02:38:53
【问题描述】:
我正在 Jest 中为一个组件进行单元测试。我要验证的功能之一是,当组件中呈现的子组件(实现ControlValueAccessor)修改其ngModel 绑定并触发父组件执行相应操作的(ngModelChange) 事件时。
为简洁起见,这里是父级的相关代码,包含对子级的引用,<child-component>:
<div>I am the parent component</div>
<child-component
[(ngModel)]="myModel"
(ngModelChange)="doAThing($event)"
>
</child-component>
在测试中我尝试过这样的测试:
it('Binds to the child properly', () => {
// Bunch of set up where I use Angular's TestBed utility to get a reference to the component
// and the testing fixture
spyOn(component, 'doAThing');
component.myModel = 'new data';
fixture.detectChanges();
expect(component.doAThing).toHaveBeenCalled();
});
但间谍从未检测到任何呼叫。现在这种方法是有道理的,因为我直接在父级上修改模型,该模型将传递给子级,但不应该备份给父级-在这种情况下,您最终会陷入递归循环。
那么问题是:我如何在父组件的 Jest 测试中使 <child-component> 触发其 (ngModelChange) 事件?
阅读文档后,我唯一的想法是 stub out the child component 并以某种方式获取对它的引用并手动触发事件。但这似乎需要做很多工作。有没有更简单的方法?
感谢您对如何最好地测试此功能的任何想法。
【问题讨论】:
标签: javascript angular testing jestjs