[英]Sails.js: Jest spyOn results in TypeError: Cannot assign to read only property
I'm trying to mock the implementation of a function call using Jest's spyOn
:我正在尝试使用 Jest 的spyOn
模拟 function 调用的实现:
await sails.helpers.models.test.randomFn.with({ ... });
const randomFnSpy = jest.spyOn(sails.helpers.models.test.randomFn, 'with');
randomFnSpy.mockImplementation(() => {});
Error:错误:
TypeError: Cannot assign to read only property 'with' of function 'function runFn(_argins, _explicitCbMaybe, _metadata){类型错误:无法分配给 function 函数 runFn(_argins, _explicitCbMaybe, _metadata){ 的只读属性“with”
I tried setting the property as configurable
and writable
:我尝试将属性设置为可configurable
和writable
:
Object.defineProperty(
sails.helpers.models.test.randomFn,
'with',
{ configurable: true, writable: true }
);
Error:错误:
TypeError: Cannot redefine property: with at Function.defineProperty ()类型错误:无法重新定义属性:在 Function.defineProperty ()
What worked to mock helpers for me:对我来说嘲笑帮手的是什么:
Sails internally uses machine
which does the following: Sails 内部使用执行以下操作的machine
:
Object.defineProperty(wetMachine, 'with', {
enumerable: false,
configurable: false,
writable: false,
value: arginStyle === 'named' ? wetMachine : wetMachine.customize({
arginStyle: 'named',
execStyle: execStyle,
extraArginsTactic: extraArginsTactic,
extraCallbacksTactic: extraCallbacksTactic,
arginValidationTactic: arginValidationTactic,
resultValidationTactic: resultValidationTactic,
finalAfterExec: finalAfterExec,
defaultMeta: defaultMeta,
defaultArgins: defaultArgins,
// Note there is no reason to pass through `implementationSniffingTactic`
// here, since it would have already applied now (it applies at build-time.)
})
});
Instead of spying on with
, mocking the helper's fn
did the trick:帮助者的fn
没有监视 mocking with
而是做了这个把戏:
jest.mock('../../../../../api/helpers/models/test/random-fn', () => ({ fn: () => {} }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.