Jasmine: Spy on value properties

Updated . Posted . Visible to the public.

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 .

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)
}
Henning Koch
Last edit
Dominic Beger
Keywords
javascript, js, test, specs, example
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2021-12-02 13:51)