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
);





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 as this context. It is strange that they wouldn't have it.
– vitaly-t
Aug 27 at 12:21


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)