[英]How to mock a decorator function used on method that is used in SUT in JEST
我有一個打字稿類:
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 框架中實現我的目標?
從技術上講,您的裝飾器是一個返回另一個函數的函數。
所以你的模擬不正確,它應該返回一個函數,試試:
myModule = require(./DecoratorFunctions);
myModule.LogThisAction = () => jest.fn();
您可以使用
笑話
模擬模塊和底層實現
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的實現
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.