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

查看:26
本文介绍了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 元素值后没有调度 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天全站免登陆