angulartypescriptkarma-jasmineangular2-testingspyon

how to get arguments on an event emitter in jasmine test


I have a unit test as below

it('billing information is correct', () => {
    fixture.detectChanges();
    spyOn(component.myEventEmitter, 'emit').and.callThrough();
    component.form.controls['size'].setValue(12);
    fixture.detectChanges();
    **let args= component.myEventEmitter.emit.mostRecentCall **
    expect(args.billingSize).toEqual('30')
});

When size changes, myEventEmitter is being emitted with a large json object which includes billingSize. And I want the test to check if this value is as expected. But looks like I can't do 'mostRecentCall/ calls' on the event emitter. What can I try next?

Note: I don't want to do expect(component.myEventEmitter.emit).toHaveBeenCalledWith(*dataExpected*) because the dataExpected is a large JSON object. I just care about one field.


Solution

  • This should work.

    it('billing information is correct', () => {
      fixture.detectChanges();
      spyOn(component.myEventEmitter, 'emit').and.callThrough();
      component.form.controls['size'].setValue(12);
      fixture.detectChanges();
      let arg: any = (component.myEventEmitter.emit as any).calls.mostRecent().args[0];
      expect(arg.billingSize).toEqual('30');
    });
    

    note:

     component.myEventEmitter.emit.calls.mostRecent() 
    

    - wouldn't compile (error: calls does not exist on type ..') so type it to 'any' and should work.