【问题标题】:I am mocking a function instance(es5) using jest but not able to mock it properly我正在使用 jest 模拟一个函数实例(es5),但无法正确模拟它
【发布时间】:2019-02-03 20:17:39
【问题描述】:

我的代码如下 ->

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 函数中访问实例?

【问题讨论】:

    标签: javascript unit-testing testing jestjs


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2021-09-05
    • 2019-03-22
    • 1970-01-01
    • 2019-08-04
    • 2022-10-05
    • 2021-11-06
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多