如何在jest模拟函数中获得`this`

时间:2017-09-11 10:11:21

标签: jestjs

我有以下代码,它会模仿fetchAge的函数Person。我需要根据this的值有条件地返回一个值,但this是函数中的空对象。有没有办法在Jest中做到这一点?

jest.unmock('Person');
const Person = require('Person');

Query.prototype.fetchAge = jest.fn(() => {
    console.log(this); // this returns an empty object
    if(this.name === 'Bob') return 21;
    if(this.name === 'Joe') return 19;
});

test('verify correct ages', function() {
  const bob = new Person('Bob');
  expect(bob.fetchAge).toEqual(21);
});

1 个答案:

答案 0 :(得分:0)

如果您不需要在模拟的fetchAge方法上声明任何内容(例如,像fetchAge.mock.calls.length),则可以简单地将fetchAge方法分配给新函数,而无需使用{{ 1}}。

例如

jest.fn

我认为Query.prototype.fetchAge = () => { console.log(this); // this returns an empty object if(this.name === 'Bob') return 21; if(this.name === 'Joe') return 19; }; 将与正确的对象(这里是this)相关。