How to test “this” calling context with jest?
How to test “this” calling context with jest?
How does one test in jest
that a function is called with the right this
context?
jest
this
I only was able to find how to test for arguments passed in, with toHaveBeenCalledWith. But it doesn't test this
context, and I can't find any other API for this or examples.
this
1 Answer
1
JEST
Create a mock of the function then use mock.instances
to check the value of this
.
mock.instances
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
For better semantics Sinon
provides direct access to this
using thisValue
.
Sinon
this
thisValue
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
);
jest
this
@vitaly-t yeah, after looking at the source it really feels like
instances
is meant to track the instances created by a constructor function like it says in the docs and wasn't intended to be used to give back this
for normal functions. I updated my answer to include Sinon
which has direct and documented support for testing this
.– brian-lives-outdoors
Aug 27 at 14:36
instances
this
Sinon
this
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That's what you call a pseudo-test. I had something similar working already, but I was hoping that
jest
had support for something as essential asthis
context. It is strange that they wouldn't have it.– vitaly-t
Aug 27 at 12:21