Angular2 Component: Testing form input value chang

2019-03-27 07:24发布

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.

So here's what i tried

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()
        })
    })

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

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.

Anyone has ideas?

2条回答
贪生不怕死
2楼-- · 2019-03-27 07:30

Triggering the value change of FormControl is as simple as:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue);
查看更多
▲ chillily
3楼-- · 2019-03-27 07:46

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();
// ...

Updating input html field from within an Angular 2 test

查看更多
登录 后发表回答