Pete B.
Pete B.

Reputation: 3286

Angular 2/Jasmine Testing a Input Field Bind

I am currently using Angular 2 and Jasmine and have a simple input field. I am attempting to write a unit test and using this examplefrom the Angular.io site. Given that it is more informative, you can see the plnkr . Look for app->dashboard->dasboard-hero.component.ts.

The example uses a select, where I am using an input and unable to get the eventEmitter to fire.

My Component:

export class MyInputComponent implements OnInit {
  private _myBind: string;
  @Output() myBindChange = new EventEmitter();

  @Input()
  set myBind(bindField: string) {
    this.myBindChange.emit(bindField);
    this._myBind = bindField;
  }

  get myBind(): string {
    return this._myBind;
  }

The HTML:

<p><input type="text"  [(ngModel)]="myBind"></p>

This works just fine when included on a demo HTML page.

The test case:

  describe('Testing the Bind', () => { 
   let fix: ComponentFixture<MyInputComponent>;
   let ele: DebugElement;  
   let comp: MyInputComponent;

     beforeEach(() => {
       fix = TestBed.createComponent(MyInputComponent);
       comp = fix.componentInstance;
       ele = fix.debugElement.query(By.css('input'));
       comp.myBind = 'Nikki';  
     });

     it('should emit when input added', () => {
       let boundString: string;
       boundString = 'zzz';  //Dummy value so bound is not null.
       comp.myBindChange.subscribe((str: string) 
            => boundString = str);  //Listen for the event.
       ele.triggerEventHandler('keypress', null);  //Is the event triggered?
       expect(boundString).toBe('Nikki');  //fails, it's still zzz.
     });  });

I could be doing something wrong, or I could be triggering the wrong event.

Is the event wrong?
Is there something wrong in my test?

BTW I will up vote good answers.

Upvotes: 0

Views: 1025

Answers (2)

Pete B.
Pete B.

Reputation: 3286

In the end I had to change one line in the test case.

Remove:

ele.triggerEventHandler('keypress', null);  //Is the event triggered?

Replace with:

ele.myBind('Nikki');

This fires the emitter, and boundString is updated allowing the test case to pass.

Upvotes: 0

Borquaye
Borquaye

Reputation: 776

Try adding a detectChanges() to your fixture after you change the value of comp.myBind

fix.detectChanges()

You can read about change detection in tests here:

https://angular.io/docs/ts/latest/guide/testing.html#!#detect-changes

Upvotes: 1

Related Questions