单元测试 – Angular2组件:测试表单输入值更改
发布时间:2020-12-17 07:13:00 所属栏目:安全 来源:网络整理
导读:我有一个文本输入,我正在听取更改. mycomponent.ts ngOnInit() { this.searchInput = new Control(); this.searchInput.valueChanges .distinctUntilChanged() .subscribe(newValue = this.search(newValue))}search(query) { // do something to search} my
|
我有一个文本输入,我正在听取更改.
mycomponent.ts ngOnInit() {
this.searchInput = new Control();
this.searchInput.valueChanges
.distinctUntilChanged()
.subscribe(newValue => this.search(newValue))
}
search(query) {
// do something to search
}
mycomponent.html <search-box>
<input type="text" [ngFormControl]="searchInput" >
</search-box>
运行应用程序一切正常,但我想对其进行单元测试. 所以这就是我的尝试 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()
})
})
测试失败,因为未调用.search()方法. 我想我必须以另一种方式设置值,让测试意识到变化,但我真的不知道如何. 有人有想法吗? 解决方法
可能有点晚了,但似乎您的代码在设置输入元素值后没有调度输入事件:
// ...
input.value = 'fake-search-query';
input.dispatchEvent(new Event('input'));
cmpFixture.detectChanges();
// ...
Updating input html field from within an Angular 2 test (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
