Angular2组件:测试表单输入值更改 [英] Angular2 Component: Testing form input value change

查看:113
本文介绍了Angular2组件:测试表单输入值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text input and i'm listening for the changes.

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>

运行该应用程序一切正常,但是我想对其进行单元测试。

Running the application everything works fine, but i want to unit-test it.

这就是我尝试过的内容

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

Test fails as the .search() method is not called.

我想我必须以另一种方式设置 value 来使测试实现更改,但是我真的不知道如何。

I guess i have to set the value in another way to have the test realize of the change but i really don't know how.

有人有想法吗?

推荐答案

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

It might be a little bit late, but it seems that your code is not dispatching input event after setting input element value:

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

从Angular 2测试中更新输入html字段

这篇关于Angular2组件:测试表单输入值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆