How do I spyOn Typescript getters and setters?

hdavidzhu picture hdavidzhu · Nov 6, 2015 · Viewed 10.4k times · Source

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.

Answer

Laoujin picture Laoujin · Jun 3, 2017

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();
});