我偶然发现了一个奇怪的问题。我正在使用基于模板的表单和双向绑定执行单元测试。这是测试代码:
describe('Template Forms Input', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BrowserModule, FormsModule],
declarations: [DummyFormsComponent],
}).compileComponents();
});
it('DOM input value changes the component model', fakeAsync(() => {
const fixture = TestBed.createComponent(DummyFormsComponent);
fixture.detectChanges();
const dummyInputDe = fixture.debugElement.query(By.css('input'));
const dummyInputEl = dummyInputDe.nativeElement;
dummyInputEl.value = 'Super dummy';
dummyInputEl.dispatchEvent(new Event('input'));
tick();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('h2')).nativeElement.textContent).toEqual('Super dummy');
}));
});
@Component({
selector: 'dummy-forms',
template: `
<form>
<input name="title" [(ngModel)]="model.anotherDummyValue">
</form>
<h2>{{model.anotherDummyValue}}</h2>
`
})
class DummyFormsComponent {
model = { anotherDummyValue: '', date: '' };
}
我无法让测试通过。 h2 始终为空。然而。如果我删除<form>
标记并仅保留视图中的输入。测试正在通过。
我认为我的异步行为做错了。有人有主意吗?
遇到了和你类似的问题(请参阅下面我的 Angular 环境详细信息),搜索了所有有关单元测试的互联网NgModel
。最后我发现将值单独设置为查询的输入(实际上是通过NgModel
) 是不足够的。 IE。dummyInputEl.value = 'Super dummy';
和dispatchEvent('input')
在你的情况下永远不会得到实际的NgModel
操作启动并运行。
Solution
为了解决这个问题,你必须得到injected NgModel
来自绑定的实例input
并通过其设置值valueAccessor
财产通过writeValue
方法,在发出之前'input'
DOM 原生元素上的事件.
...
const ngModel = dummyInputDe.injector.get(NgModel);
tick(); // <== Important to wait until stable before writing value
ngModel.valueAccessor.writeValue('Super dummy');
dummyInputDe.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges(); // <= force updates to the view
expect(fixture.debugElement.query(By.css('h2'))
.nativeElement.textContent).toEqual('Super dummy'); // <= Viola!
...
请注意,我们必须提供tick
在 - 的里面fakeAsync
在写信之前NgModel
值访问器。可能是因为 NgModel 的访问器需要一段时间才能准备好,然后才能在其上写入值(在这方面感谢反馈).
虽然在规格没有的情况下fakeAsync
区,相同的情况应该用fixture.whenStable()
决心承诺得到所需的结果。
Note:关于网络上单元测试的每个主题,尤其是当NgModel
是有问题的,这在任何地方都没有提到。甚至连 Angular 官方文档都没有。不确定新的 Angular 版本是否(特别是变化FormsModule
执行)迫使这一改变。
角度环境设置
- 角
v5.2.0
- 业力
v2.0.0
- 茉莉花(茉莉花芯)
v2.8.0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)