Sails.js: Jest spyOn results in TypeError: Cannot assign to read only property
Sails.js: Jest spyOn results in TypeError: Cannot assign to read only property
我正在尝试使用 Jest 的 spyOn
:
模拟函数调用的实现
await sails.helpers.models.test.randomFn.with({ ... });
const randomFnSpy = jest.spyOn(sails.helpers.models.test.randomFn, 'with');
randomFnSpy.mockImplementation(() => {});
错误:
TypeError: Cannot assign to read only property 'with' of function 'function runFn(_argins, _explicitCbMaybe, _metadata){
我尝试将 属性 设置为 configurable
和 writable
:
Object.defineProperty(
sails.helpers.models.test.randomFn,
'with',
{ configurable: true, writable: true }
);
错误:
TypeError: Cannot redefine property: with
at Function.defineProperty ()
对我来说模拟助手的方法:
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.)
})
});
不是监视 with
,而是嘲笑助手的 fn
成功了:
jest.mock('../../../../../api/helpers/models/test/random-fn', () => ({ fn: () => {} }));
我正在尝试使用 Jest 的 spyOn
:
await sails.helpers.models.test.randomFn.with({ ... });
const randomFnSpy = jest.spyOn(sails.helpers.models.test.randomFn, 'with');
randomFnSpy.mockImplementation(() => {});
错误:
TypeError: Cannot assign to read only property 'with' of function 'function runFn(_argins, _explicitCbMaybe, _metadata){
我尝试将 属性 设置为 configurable
和 writable
:
Object.defineProperty(
sails.helpers.models.test.randomFn,
'with',
{ configurable: true, writable: true }
);
错误:
TypeError: Cannot redefine property: with at Function.defineProperty ()
对我来说模拟助手的方法:
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.)
})
});
不是监视 with
,而是嘲笑助手的 fn
成功了:
jest.mock('../../../../../api/helpers/models/test/random-fn', () => ({ fn: () => {} }));