How do I spyOn Typescript getters and setters?

孤街醉人 提交于 2021-02-07 11:38:13

问题


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.


回答1:


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



回答2:


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



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/33576096/how-do-i-spyon-typescript-getters-and-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!