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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)