Bol*_*lza 9 unit-testing angular2-forms angular2-testing angular2-components angular
我有一个文本输入,我正在听取更改.
mycomponent.ts
ngOnInit() {
this.searchInput = new Control();
this.searchInput.valueChanges
.distinctUntilChanged()
.subscribe(newValue => this.search(newValue))
}
search(query) {
// do something to search
}
Run Code Online (Sandbox Code Playgroud)
mycomponent.html
<search-box>
<input type="text" [ngFormControl]="searchInput" >
</search-box>
Run Code Online (Sandbox Code Playgroud)
运行应用程序一切正常,但我想对其进行单元测试.
所以这就是我的尝试
mycomponent.spec.ts
beforeEach(done => {
createComponent().then(fix => {
cmpFixture = fix
mockResponse()
instance = cmpFixture.componentInstance
cmpFixture.detectChanges();
done();
})
})
describe('on searching on the list', () => {
let compiled, input
beforeEach(() => {
cmpFixture.detectChanges();
compiled = cmpFixture.debugElement.nativeElement;
spyOn(instance, 'search').and.callThrough()
input = compiled.querySelector('search-box > input')
input.value = 'fake-search-query'
cmpFixture.detectChanges();
})
it('should call the .search() method', () => {
expect(instance.search).toHaveBeenCalled()
})
})
Run Code Online (Sandbox Code Playgroud)
测试失败,因为.search()未调用该方法.
我想我必须设置value另一种方式让测试意识到变化,但我真的不知道如何.
有人有想法吗?
And*_*ius 21
它可能有点晚了,但似乎你的代码input在设置输入元素值后没有调度事件:
// ...
input.value = 'fake-search-query';
input.dispatchEvent(new Event('input'));
cmpFixture.detectChanges();
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9444 次 |
| 最近记录: |