Jasmine: Expecting objects as method invocation arguments

Updated . Posted . Visible to the public.

To check if a method has been called in Jasmine, you first need to spy on it:

let spy = spyOn(window, 'alert')
codeThatAlerts()
expect(window.alert).toHaveBeenCalledWith('Important message')

To expect an object of a given type, pass the constructor function to jasmine.any():

expect(spy).toHaveBeenCalledWith(jasmine.any(Object))
expect(spy).toHaveBeenCalledWith(jasmine.any(String))
expect(spy).toHaveBeenCalledWith(jasmine.any(Number))

To expect an object with given key/value properties, use jasmine.objectContaining():

expect(spy).toHaveBeenCalledWith(jasmine.objectContaining(name: 'John Doe'))

To expect any value:

expect(spy).toHaveBeenCalledWith(jasmine.anything())

Note that if you want compare an existing value instead of an invocation argument, toEqual() works with partial matchers:

expect(value).toEqual(jasmine.any(String))
Profile picture of Henning Koch
Henning Koch
Last edit
Fabian Schwarz
Keywords
javascript, partial
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2017-11-19 16:27)