get the arguments with which a spy was called
Asked Answered
Z

2

5

I am spying on method emit of EventEmitter in Angular

spyOn(answerComponent.answerEmitter, 'emit');

I want to check that emit was called with an argument A but I don't want to check exact match with A. I want to check that emit was called with values A.a, A.b and ignore value of A.c.

Is it possible to do so?

Zooplasty answered 28/12, 2020 at 12:16 Comment(0)
S
7

Use jasmine.objectContaining.

const emit = spyOn(answerComponent.answerEmitter, 'emit');
expect(emit).toHaveBeenCalledWith(jasmine.objectContaining({ a: <value>, b: <value>));
Speak answered 12/7, 2022 at 22:27 Comment(1)
For functions, it also works with the jasmine object: expect(<something>).toHaveBeenCalledWith('some-param', jasmine.any(Function)) :)Attract
A
1

Two ways come to my mind:

One by using the native toHaveBeenCalledWith

expect(answerComponent.answerEmitter, 'emit').toHaveBeenCalledWith(A.a);
expect(answerComponent.answerEmitter, 'emit').toHaveBeenCalledWith(A.b);
// you can think of all the callers being tracked as an array and you can assert with
// toHaveBeenCalledWith to check the array of all of the calls and see the arguments
expect(anserComponent.anserEmitter, 'emit').not.toHaveBeenCalledWith(A.c); // maybe you're looking for this as well

You can also spy on the emit and call a fake function:

spyOn(answerComponent.answerEmitter, 'emit').and.callFake((arg: any) => {
  // every time emit is called, this fake function is called
  if (arg !== A.a || arg !== A.b) {
     throw 'Wrong argument passed!!'; // you can refine this call fake
  }  // but the point is that you can have a handle on the argument passed and assert it
});
Archdiocese answered 29/12, 2020 at 2:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.