如何用玩笑来测试“ this”调用上下文?

时间:2018-08-26 14:42:12

标签: jestjs

如何在jest中测试在正确的this上下文中调用了一个函数?

我只能使用toHaveBeenCalledWith找到如何测试传入的参数。但这无法测试this上下文,因此我无法为此或示例找到其他任何API。

1 个答案:

答案 0 :(得分:2)

JEST

创建函数的mock,然后使用mock.instances to check the value of this

test('the value of this using Jest', () => {
  const foo = {
    name: 'foo',
    func: function() {
      return `my name is ${this.name}`;
    }
  }
  const mockFunc = jest.spyOn(foo, 'func'); // spy on foo.func()

  expect(foo.func()).toBe('my name is foo');
  expect(mockFunc.mock.instances[0]).toBe(foo); // called on foo

  mockFunc.mockClear();

  const bar = {
    name: 'bar',
    func: foo.func // use the func from foo
  }

  expect(bar.func()).toBe('my name is bar');
  expect(mockFunc.mock.instances[0]).toBe(bar); // called on bar
});

SINON

为了获得更好的语义,Sinon使用thisValue提供对this的直接访问。

import * as sinon from 'sinon';

test('the value of this using Sinon', () => {
  const foo = {
    name: 'foo',
    func: function() {
      return `my name is ${this.name}`;
    }
  }
  const spy = sinon.spy(foo, 'func'); // spy on foo.func()

  expect(foo.func()).toBe('my name is foo');
  expect(spy.lastCall.thisValue).toBe(foo); // called on foo

  const bar = {
    name: 'bar',
    func: foo.func // use the func from foo
  }

  expect(bar.func()).toBe('my name is bar');
  expect(spy.lastCall.thisValue).toBe(bar); // called on bar
});