Home > front end >  Is there a way to access this (current instance) from within jest spyOn mockImplementation?
Is there a way to access this (current instance) from within jest spyOn mockImplementation?

Time:01-22

On my test suite I did the following to mock a class method:

beforeEach(() => {
    jest
      .spyOn(MyClass.prototype, "loadVars")
      .mockImplementation(async () => {

        const file:string = `MyClass.${
          this.prefix  // <---- how can I address this?
        }.data.mock.json`;
        logger.info(`Mocking all parameters from ${file}`);

        return JSON.parse(
          fs.readFileSync(
            process.cwd()   `/../data/${file}`,
            "utf-8"
          )
        );
      });
  });

Is there a way to ref to the current class instance from within this mock?

CodePudding user response:

Arrow functions () => {} capture the value of this from their declaring scope. So to replace a prototype method, you need to use a function statement.

Also, Typescript needs a hint here about what this is expected to be, so you can set a type for this.

I think this should do what you expect:

jest
  .spyOn(MyClass.prototype, 'loadVars')
  .mockImplementation(function (this: MyClass) {
    console.log(this.prefix) // works
  })
  •  Tags:  
  • Related