After upgrading to Angular 9 (from 8.1) and Typescript 3.7 (from <3.6), I've come across an issue with the spyOnProperty
method.
This is how my service looks:
class Backend {
public get baseURL(): string {
return 'http://baseurl.com/';
}
}
Previously, my test that used spyOnProperty
worked fine:
spyOnProperty(backend, 'baseURL', 'get').and.returnValue('http://new');
However, now I'm facing this error:
Error: <spyOnProperty> : baseURL is not declared configurable
Usage: spyOnProperty(<object>, <propName>, [accessType])
I understand that I need to set configurable: true
using Object.defineProperty
, as the error seems to be related to:
if (!descriptor.configurable) {
throw new Error(
getErrorMsg(propertyName + ' is not declared configurable')
);
}
The descriptor
is created by
descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
In Javascript, you would do something like this:
Object.defineProperty(backend.prototype, 'baseURL', {value: 'http://new', configurable: true});
But my question is, how can I achieve the same in Typescript? Attempting to use Object.defineProperty
again results in a
defineproperty Cannot redefine property
error, which makes sense given the initial check in place.
I tried using the suggested configurable
decorator described here:
function configurable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.configurable = value;
};
}
Unfortunately, this approach didn't work for me. Also, when debugging inside the mentioned method, I noticed that descriptor.configurable
was already set to true
before assigning the value
. So, I'm unsure of what exactly is causing the original error in my tests.