我有一个打字稿课:
export class SystemUnderTest {
@LogThisAction('sth was done')
public doSomething() {}
}
如您所见,它使用反射来执行一些装饰功能:
export declare function LogThisAction(action: string): (target: any) =>
void;
当我进行测试时,我并不在乎实际的影响。装饰器函数的功能,所以我尝试这样模拟它:
myModule = require(./DecoratorFunctions);
myModule.LogThisAction = jest.fn();
但这似乎不起作用。当我运行测试时,我得到:
● Test suite failed to run
TypeError: decorator is not a function
at DecorateProperty (node_modules/reflect-metadata/Reflect.js:553:33)
如何在JEST框架中实现我的目标?
答案 0 :(得分:1)
您的装饰器从技术上讲是一个功能,返回另一个功能。
因此您的模拟不正确,它应该返回一个函数,请尝试以下操作:
myModule = require(./DecoratorFunctions);
myModule.LogThisAction = () => jest.fn();
答案 1 :(得分:0)
您可以使用
jest.mock
模拟模块和基础实现
jest.mock('./DecoratorFunctions', () => ({ LogThisAction: (item: any) => {
return (target, propertyKey, descriptor) => {
// save a reference to the original method
const originalMethod = descriptor.value as () => Promise<any>;
descriptor.value = async function(...args) {
originalMethod.apply(this, args);
return response;
};
return descriptor;
}; }}));
这将模拟 LogThisAction
的实现