繁体   English   中英

如何模拟在 JEST 中的 SUT 中使用的方法上使用的装饰器函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM