简体   繁体   English

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

[英]How to mock a decorator function used on method that is used in SUT in JEST

I have a typescript class:我有一个打字稿类:

export class SystemUnderTest {

  @LogThisAction('sth was done')
  public doSomething() {} 

}

As you can see it uses a reflection to execute some decoration function:如您所见,它使用反射来执行一些装饰功能:

 export declare function LogThisAction(action: string): (target: any) => 
 void;

When I run test in I do not care about the actual impl.当我运行测试时,我不关心实际的实现。 of this decorator function, so I try to mock it like this:这个装饰器函数,所以我尝试像这样模拟它:

 myModule = require(./DecoratorFunctions);
 myModule.LogThisAction = jest.fn();

But that does not seem to work.但这似乎不起作用。 When I run tests I get:当我运行测试时,我得到:

● Test suite failed to run
TypeError: decorator is not a function
at DecorateProperty (node_modules/reflect-metadata/Reflect.js:553:33)

How to achieve my goal in JEST framework ?如何在 JEST 框架中实现我的目标?

Your decorator is technically a function which is returning another function.从技术上讲,您的装饰器是一个返回另一个函数的函数。

So your mock is not correct and it should return a function, try it with:所以你的模拟不正确,它应该返回一个函数,试试:

myModule = require(./DecoratorFunctions);
myModule.LogThisAction = () => jest.fn();

You can use the您可以使用

jest.mock笑话

to mock the module and the underlying implementation模拟模块和底层实现

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;
}; }}));

This will mock the implementation of LogThisAction这将模拟LogThisAction的实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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