EnlitenedZA
EnlitenedZA

Reputation: 149

Angular 2 testing with ngModel and ngModelChange

I am trying to test a wrapper component around a text input.

My component looks like this:

@Component({
selector: 'my-textbox',
inputs: ['inputModel', 'label'],
outputs: ['inputModelChange'],    
template: `  

    <div ngForm class="field">
        <label>{{ label }}</label>            
        <input type="text" ngControl="{{ control }}" #item="ngForm" [ngModel]="inputModel" (ngModelChange)="setTextValue($event)">
    </div>
    `
})

export class IslTextboxComponent {

control;
inputModel: Object;
inputModelChange: EventEmitter<any> = new EventEmitter();
label: string;

constructor() {
    this.control = 'text'+ Math.floor(Math.random()*11);
}

setTextValue(newValue): void {
    this.inputModel = newValue;
    this.inputModelChange.emit(newValue);
}
}

And here is my test:

describe('My Textbox Component', () => {

it('should show modify input model',
    injectAsync([TestComponentBuilder], (tcb) => {
        return tcb
            .createAsync(MyTextboxComponent)
            .then((fixture) => {

                let nativeElement = fixture.nativeElement;

                fixture.detectChanges();                   

                let input = nativeElement.querySelector('input');

                input.value = 'VALUE_TO_TEST';

                //???
                input.dispatchEvent(new Event('input'));                    

                fixture.detectChanges();                                  

                expect(nativeElement.inputModel).toBe('VALUE_TO_TEST');

            });
    }));

});

I want to input text into the textbox and have the inputModel update itself but the event is not being fired. How can I make the ngModelChange event fire? The inputModel is never updated...

Upvotes: 3

Views: 5438

Answers (1)

Dennis Neuendorf
Dennis Neuendorf

Reputation: 41

let input = nativeElement.querySelector('input');
input.value = 'VALUE_TO_TEST';
let evt = document.createEvent('Event');
evt.initEvent('input', true, false);
setTimeout(expect(x).ToBe(z),1000);

You were nearly there.

  • The setTimeout is about get the Change-Detection a second to run. (Can be reduced later).
  • createEvent takes the EventInterface-Name as param and initEvent is defining it. "Event" is the most basic one with no payload.
  • changeDetection isn't needed to be triggered manually after the input because you trigger an event on the view.

Upvotes: 2

Related Questions