我的代码如下->

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


当我实例化此函数时,如下所示

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


我该如何在mockImplementation函数中访问实例?

最佳答案

箭头函数具有词法范围,因此this不会引用您的mockFunction对象。您应该将回调更改为常规函数,如下所示:

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

10-06 12:12