Angular2组件:测试表单输入值更改

时间:2016-05-20 17:16:25

标签: unit-testing angular angular2-forms angular2-components angular2-testing

我有一个文本输入,我正在听取更改。

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()方法。

我想我必须以另一种方式设置value让测试意识到变化,但我真的不知道如何。

有人有想法吗?

2 个答案:

答案 0 :(得分:19)

可能有点晚了,但似乎您的代码在设置输入元素值后没有调度input事件:

// ...    
input.value = 'fake-search-query';
input.dispatchEvent(new Event('input'));
cmpFixture.detectChanges();
// ...

Updating input html field from within an Angular 2 test

答案 1 :(得分:1)

触发FormControl的值更改非常简单:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue);