0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That did not work, I found a very simple solution. It helps typing it up to ask the question.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.