Read more

Jasmine: Expecting objects as method invocation arguments

Henning Koch
November 19, 2017Software engineer at makandra GmbH

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')
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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))
Posted by Henning Koch to makandra dev (2017-11-19 17:27)