When I unit test my getters are setters for Typescript, I cannot find a way to spy on those getters and setters. Instead, the object immediately gets evaluated. I am using Jasmine to unit test.
Asked
Active
Viewed 1.7k times
14
-
Duplicate of https://stackoverflow.com/questions/20879990 – goWithSwagger Oct 17 '17 at 13:21
4 Answers
29
spyOnProperty
is now available in Jasmine:
const foop = {
get value() {},
set value(v) {}
};
it('can spy on getter', () => {
spyOnProperty(foop, 'value', 'get').and.returnValue(1);
expect(foop.value).toBe(1);
});
it('and on setters', () => {
const spiez = spyOnProperty(foop, 'value', 'set');
foop.value = true;
expect(spiez).toHaveBeenCalled();
});

Laoujin
- 9,962
- 7
- 42
- 69
-
I am trying this, spyOnProperty(component, 'name', 'get').and.returnValue(1); expect(component.name).toBe(1); But it keeps throwing the error: component.name is not a function – cheesydoritosandkale Jun 12 '20 at 13:31
-
3
It is not supported yet, but there is a Jasmine issue for supporting getters.
If you really need the support now, you can extend SpyRegistry.js file and add the code that apsillers proposed:
this.spyOnProperty = function(obj, methodName, accessType) {
...
var desc = Object.getPropertyDescriptor(obj, methodName);
if(desc[accessType]) { // "get" or "set" exists on the property
var spy = j$.createSpy(methodName, desc[accessType]);
desc[accessType] = spy;
Object.defineProperty(obj, methodName, desc);
}
}

MartyIX
- 27,828
- 29
- 136
- 207
2
I cannot find a way to spy on those getters and setters. Instead, the object immediately gets evaluated.
That is not supported by Jasmine. Your primary options are to refactor into function calls OR extend jasmine

basarat
- 261,912
- 58
- 460
- 511
-
1I believe it still is not, in 2020. Running into test framework limitations like this is... basically just embarrassing :/ – Michahell Jun 10 '20 at 09:03
0
I found the solution here helpful. Instead of spying on the getter, just overriding it to modify the return for testing.

theUtherSide
- 3,338
- 4
- 36
- 35