Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spyOn functionality #1749

Closed
jardakotesovec opened this issue Sep 20, 2016 · 4 comments
Closed

spyOn functionality #1749

jardakotesovec opened this issue Sep 20, 2016 · 4 comments

Comments

@jardakotesovec
Copy link

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.

@cpojer
Copy link
Member

cpojer commented Sep 21, 2016

This is tracked as part of #1679.

@cpojer cpojer closed this as completed Sep 21, 2016
@navgarcha
Copy link

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?

@AndersDJohnson
Copy link

See also #2534.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 13, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants