Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Component: Testing form input value change

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?

like image 612
Bolza Avatar asked May 20 '16 17:05

Bolza


People also ask

What is fixture detectChanges?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement. textContent.

What is fixture DebugElement?

DebugElement is an Angular class that contains all kinds of references and methods relevant to investigate an element as well as component fixture.debugElement.query(By.css('#shan'))


2 Answers

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

like image 153
Andrius Avatar answered Oct 20 '22 00:10

Andrius


Triggering the value change of FormControl is as simple as:

cmpFixture.debugElement.componentInstance.searchInput.setValue(newValue);
like image 35
kimamula Avatar answered Oct 19 '22 23:10

kimamula