Read more

Jasmine: Spy on value properties

Henning Koch
December 02, 2021Software engineer at makandra GmbH

Jasmine has spyOnProperty() Show archive.org snapshot , but it only works if the property is implemented using getter and setter functions. This is a known limitation of Jasmine Show archive.org snapshot .

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

If the mocked property is a simple value, it will not work:

const x = { foo: 1 }
console.log(x.foo) // 1
spyOnProperty(x, 'foo').and.returnValue(2)
// Throws: Error: <spyOnProperty> : Property foo does not have access type get

Below you can find a function spyOnValueProperty() that converts a value property to getters and setters so it can be mocked with Jasmine. You can use it like this:

const x = { foo: 1 }
console.log(x.foo) // 1
spyOnValueProperty(x, 'foo').and.returnValue(2)
expect(x.foo).toBe(2)

Here is the spyOnValueProperty() function:

window.spyOnValueProperty = function(obj, prop, accessType = 'get') {
  let descriptor = jasmine.util.getPropertyDescriptor(obj, prop)
  let value = descriptor.value
  let newDescriptor = {
    ...descriptor,
    get: () => value,
    set: (newValue) => value = newValue
  }
  delete newDescriptor.value
  delete newDescriptor.writable
  Object.defineProperty(obj, prop, newDescriptor)
  return spyOnProperty(obj, prop, accessType)
}
Posted by Henning Koch to makandra dev (2021-12-02 14:51)