[英]Angular2 Component: Testing form input value change
我有一個文本輸入,我正在監聽更改。
mycomponent.ts
ngOnInit() {
this.searchInput = new Control();
this.searchInput.valueChanges
.distinctUntilChanged()
.subscribe(newValue => this.search(newValue))
}
search(query) {
// do something to search
}
我的組件.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()
方法沒有被調用。
我想我必須以另一種方式設置value
才能讓測試實現更改,但我真的不知道如何。
有人有想法嗎?
它可能有點晚了,但似乎你的代碼在設置輸入元素值后沒有調度input
事件:
// ...
input.value = 'fake-search-query';
input.dispatchEvent(new Event('input'));
cmpFixture.detectChanges();
// ...
觸發FormControl
的值更改非常簡單:
cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue);
如果你有一個自定義組件,你需要在你的應用程序中做進一步的改變才能成功地對你的應用程序進行單元測試
看看這里的要點,這會給你一些想法https://gist.github.com/AikoPath/050ad0ffb91d628d4b10ef81736af386/raw/846c7bcfc54be8cce78eba8d12015bf749b91eeejsUnTest@ViewComponent()。
在這里仔細閱讀更多完整的內容,否則您很容易再次感到困惑 - https://betterprogramming.pub/testing-angular-components-with-input-3bd6c07cfaf6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.