14

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.

dot_zero
  • 1,030
  • 3
  • 12
  • 26

4 Answers4

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
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
  • 1
    I 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.

https://stackoverflow.com/a/26888312/1341825

theUtherSide
  • 3,338
  • 4
  • 36
  • 35