100

With Jasmine, I could spy on methods and figure out the arguments. I want to be able to call toHaveBeenCalledWith(something, anything).

Let's say I want to spy on a method .on(event, callback). All I care about is if the event is listened to rather than what the actual callback identity is. Is it possible to do this without writing a custom matcher? I don't see one.

Charles
  • 50,943
  • 13
  • 104
  • 142
Pwnna
  • 9,178
  • 21
  • 65
  • 91
  • Similar question for jest is https://stackoverflow.com/questions/52337116/loose-match-one-value-in-jest-tohavebeencalledwith/67193668#67193668 – Michael Freidgeim Oct 19 '21 at 16:18

3 Answers3

134

Try

toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Function))
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
62

Jasmine 2:

 expect(callback).toHaveBeenCalledWith(jasmine.objectContaining({
    bar: "baz"
  }));

https://jasmine.github.io/api/edge/jasmine.html#.objectContaining

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
Ievgen Martynov
  • 7,870
  • 8
  • 36
  • 52
26

If you wish to test for specific things, you can do something like:

expect(mockSomething.someMethod.mostRecentCall.args[0].pool.maxSockets).toEqual(50);

The syntax in Jasmine 2 is now:

mockSomething.someMethod.calls.mostRecent().args[0]
Jesse
  • 3,522
  • 6
  • 25
  • 40
Cmag
  • 14,946
  • 25
  • 89
  • 140
  • 7
    Useful for additional optional arguments. Note the syntax in Jasmine 2 is now `mockSomething.someMethod.calls.mostRecent().args[0]` – John McCarthy Mar 15 '16 at 03:33
  • let spy = spyOn(nameService, 'getName').and.returnValue(Observable.of('Ali')); nameService.getName('Henry'); expect(spy.calls.all()[0].args[0]).toEqual('Henry'); – oomer Mar 08 '22 at 17:38