Jasmine: Expecting objects as method invocation arguments

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))
Henning Koch Over 6 years ago