微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐