If I try to spy on a getter with
spyOn(instance,'foo','get').and.returnValue(false);
I get the error
<spyOn> : foo property does not exist
Usage: spyOn(<object>, <methodName>)
22 | var instance = new MyClass();
23 |
> 24 | spyOn(instance,'foo','get').and.returnValue(false);
| ^
25 | expect(instance.foo).toBe(false);
26 |
27 | });
at SpyRegistry._spyOnProperty (node_modules/jest-jasmine2/build/jasmine/spyRegistry.js:191:15)
at Object.<anonymous> (test/tools/wizard/demo.test.js:24:5)
Here are two examples, one for a static property and one for an instance property. The first test works. The second fails.
it('static getter', ()=>{
class MyClass {
static get foo(){
return true;
}
}
spyOn(MyClass,'foo','get').and.returnValue(false);
expect(MyClass.foo).toBe(false);
});
it('non-static getter', ()=>{
class MyClass {
get foo(){
return true;
}
}
var instance = new MyClass();
spyOn(instance,'foo','get').and.returnValue(false);
expect(instance.foo).toBe(false);
});
My babel-setting inside package.json are:
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
],
"@babel/preset-react"
]
},
The instance property "foo" should be found and the second test should work, too.
npx: installed 1 in 2.149s
System:
OS: Windows 10 10.0.17763
CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Binaries:
Node: 12.13.1 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.12.1 - C:\Program Files\nodejs\npm.CMD
npmPackages:
jest: 25.1.0 => 25.1.0
https://github.com/facebook/jest/issues/8137
https://github.com/facebook/jest/issues/5746
https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname-accesstype
Inststead of
spyOn(instance,'foo','get').and.returnValue(false);
I am able to use
Object.defineProperty(instance, 'foo', { get(){ return false; } });
I have this issue as well. The workaround works but it would nice if spyOn also worked for instance properties.
dang! it's at least nice when the last comment is less than 2 weeks ago. thanks for the workaround. seems a bit janky though!
Most helpful comment
dang! it's at least nice when the last comment is less than 2 weeks ago. thanks for the workaround. seems a bit janky though!