1

My code is as below ->

let mockFunction = jest.fn().mockImplementation((a) => {
    this.temp = a;
});

When I instantiate this function as follows

let mockFn = new mockFunction(6);
console.log(mockFn.temp) //this gives me undefined instead of 6

How can I access the instance in the mockImplementation function?

Canta
  • 1,480
  • 1
  • 13
  • 26

1 Answers1

2

Arrow functions are lexically scoped, so this won't refer to your mockFunction object. You should change the callback to a regular function like so:

let mockFunction = jest.fn().mockImplementation(function(a) {
  this.temp = a;
});
kamoroso94
  • 1,713
  • 1
  • 16
  • 19
  • To further explain, the arrow functions doesn't have a constructor so they cant be used with new. https://stackoverflow.com/questions/37587834/javascript-es6-why-i-can-not-use-new-with-arrow-function – Nimit Aggarwal Aug 30 '18 at 07:26