How can I spy on a getter property using jasmine?
var o = { get foo() {}, };
spyOn(o, \'foo\').and.returnValue(\'bar\'); // Doesn\'t work.
I took inspiration from @apsillers response and wrote the following helper (requires the prop to be configurable as mentioned above)
let activeSpies = [];
let handlerInstalled = false;
function afterHandler() {
activeSpies.forEach(({ obj, prop, descriptor }) => Object.defineProperty(obj, prop, descriptor));
activeSpies = [];
}
export function spyOnGetter(obj, prop) {
const env = jasmine.getEnv();
const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
const spy = jasmine.createSpy(`${prop} spy`);
const copy = Object.assign({}, descriptor, { get: spy });
Object.defineProperty(obj, prop, copy);
activeSpies.push({
obj,
prop,
descriptor,
});
if (!handlerInstalled) {
handlerInstalled = true;
env.afterEach(() => afterHandler());
}
return spy;
}
And it can be used like so:
import { spyOnGetter } from spyExtra;
it('tests the thing', () => {
spyOnGetter(myObj, 'myProp').and.returnValue(42);
expect(myObj.myProp).toBe(42);
});
Hope it's useful!