简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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