5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Josf
  • 776
  • 1
  • 8
  • 21

2 Answers2

6

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.

Josf
  • 776
  • 1
  • 8
  • 21
0

You can also use

 expect(component.myEventEmitter.emit).toHaveBeenCalledWith('eventName', 
  jasmine.objectContaining(*dataExpected*)
);
Alexey Kucherenko
  • 885
  • 1
  • 8
  • 11
  • But looks like objectContaining expects the entire object. ( whole json object in my case). Can you provide an example? – Josf Oct 27 '17 at 01:16
  • @SoJosf You can take a look here https://github.com/robtweed/ewd-document-store/blob/master/spec/unit/proto/delete.spec.js#L52 I wrote these tests – Alexey Kucherenko Oct 27 '17 at 12:56
  • I have tried it. _expect(component.taskRowData.emit).toHaveBeenCalledWith(jasmine.objectContaining({ billingSize: 30 }));_ But think that is not quite useful in my case. The args in the eventEmitter looks like '{ taskRow: {'jsonobject'}, formValid: true}' The field I want to look for is inside 'jsonobject'. I got this error: _Expected spy emit to have been called with [ ] but actual calls were [ Object({ taskRow: Object({ id: 1, name: 'Test task', billable: false, billingSize: 30, billingPrice: 26.46_ ... – Josf Oct 29 '17 at 19:27
  • expect(component.taskRowData.emit).toHaveBeenCalledWith({ taskRow: jasmine.objectContaining({ billingSize: 30 }) }) ); – Alexey Kucherenko Oct 30 '17 at 15:10
  • Thanks Alexey for looking at this. But I am getting the same error with objectContaining. – Josf Oct 31 '17 at 03:04