How to spyOn a value property (rather than a method) with Jasmine
In February 2017, they merged a PR adding this feature, they released in April 2017.
so to spy on getters/setters you use:const spy = spyOnProperty(myObj, 'myGetterName', 'get');
where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {}
and the third param is the type get
or set
.
You can use the same assertions that you already use with the spies created with spyOn
.
So you can for example:
const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.
Here's the line in the github source code where this method is available if you are interested.
And the spyOnProperty method is here
Answering the original question, with jasmine 2.6.1, you would:
const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);expect(myObj.valueA).toBe(1);expect(spy).toHaveBeenCalled();
Any reason you cannot just change it on the object directly? It is not as if javascript enforces visibility of a property on an object.
Jasmine doesn't have that functionality, but you might be able to hack something together using Object.defineProperty
.
You could refactor your code to use a getter function, then spy on the getter.
spyOn(myObj, 'getValueA').andReturn(1);expect(myObj.getValueA()).toBe(1);