Property Spies

Learn how to use a spy to mock properties on an object.

Jasmine lets us mock specific properties on an object. We could choose to mock some or all of the values. When we spy on a property, we must mock the accessor methods. We can choose to mock the getter, setter, or both. We can write a spy by calling the spyOnProperty function and providing it the three following arguments:

  • The object we want to spy on.
  • The property name.
  • The access type that we want to mock. It can be either get or set in order to spy on the getter or setter, respectively.

In the example code below, on line 2, we use the spyOnProperty method to spy on the getter for the attempts property of the taskRunner object. We use the returnValue method to create a mock that will always return the same value. On line 6, we can still set the value of the attempts property as normal. However, when we read the property on line 9, the getter returns the mock value.

Get hands-on with 1200+ tech skills courses.