Jest: spyOn functionality

Created on 20 Sep 2016  ·  3Comments  ·  Source: facebook/jest

I am trying to figure out how to best approach following use case in jest.

I don't want to mock function, just spy on it and let original implementation do the work. Lets say I want to track how many times query was called on postgres driver. Following approach works:

const querySpy = pg.Client.prototype.query = jest.fn(pg.Client.prototype.query);
expect(querySpy.mock.calls.length).toBe(2)

Issue is that I also have to assign original implementation at the end of the test so it does not affect others in same file. So its simple to break test isolation if one person forget such clean up.

I also noticed that jasmine have spyOn which seems to work in jest as well (but not documented), which is pretty elegant, so same thing can be achieved by:

const querySpy = spyOn(pg.Client.prototype, 'query').and.callThrough();
expect(querySpy.calls.count()).toEqual(3);

And jasmine claim to remove the spy after the test automatically, which is awesome.

But not sure if thats something that will become official part of jest? Issue is that jasmine spies have different interface than mocks in jest. So I think best would be just to extend mock functionality so it can be easily used for spying using spyOn or something similar.

Any feedback welcomed.

Most helpful comment

Maybe incorrect about this but isn't the expect.spyOn different to jasmines spyOn in that it doesn't do the claimed 'automatic restore' at the end of a test? I think this feature is pretty neat and clears up the spec files. Will there be any plans to add this sort of functionally on when integrating #1679?

All 3 comments

This is tracked as part of #1679.

Maybe incorrect about this but isn't the expect.spyOn different to jasmines spyOn in that it doesn't do the claimed 'automatic restore' at the end of a test? I think this feature is pretty neat and clears up the spec files. Will there be any plans to add this sort of functionally on when integrating #1679?

See also #2534.

Was this page helpful?
0 / 5 - 0 ratings