如何在jest
中测试在正确的this
上下文中调用了一个函数?
我只能使用toHaveBeenCalledWith找到如何测试传入的参数。但这无法测试this
上下文,因此我无法为此或示例找到其他任何API。
答案 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
});