问题
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