How can I spy on a getter property using jasmine?
var o = { get foo() {}, };
spyOn(o, 'foo').and.returnValue('bar'); // Doesn't work.
This also does not work AFAICT:
spyOn(Object.getOwnPropertyDescriptor(o, 'foo'), 'get').and.returnValue('bar');
I took inspiration from @apsillers response and wrote the following helper (requires the prop to be configurable as mentioned above)
And it can be used like so:
Hope it's useful!
You can do this if you are unable to use the latest jasmine (2.6.1)
Documentation for defineProperty, here
I think the best way is to use
spyOnProperty
. It expects 3 properties and you need to passget
orset
as third property.In February 2017, they merged a PR adding this feature, they released it 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 asget myGetterName() {}
and the third param is the typeget
orset
.You can use the same assertions that you already use with the spies created with
spyOn
.So you can for example:
Here's the line in the github source code where this method is available if you are interested.
https://github.com/jasmine/jasmine/blob/7f8f2b5e7a7af70d7f6b629331eb6fe0a7cb9279/src/core/requireInterface.js#L199
Answering the original question, with jasmine 2.6.1, you would:
I don't believe you can spy on getters. The point of a getter is that it acts exactly like a property, so how would jasmine be able to spy on it when it is never called like a function but rather is accessed like a property.
As a workaround, you could have your getter call another function and spy on that instead.
Since Jasmine 2.6, this has been possible with
spyOnProperty
. To spy on the accessors for thefoo
property, do:This allows you to replace the
set
and/orget
accessor functions for an accessor property with a spy function. You can specify orset
orget
only as a third argument:If you are stuck using an earlier version and cannot upgrade for some reason, you may be able to merge the pull request that added this feature into your local copy of the code.