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

[Bug]: spy.mockReset() breaks following mock usage #15435

Open
alexey-kozlenkov opened this issue Dec 31, 2024 · 1 comment
Open

[Bug]: spy.mockReset() breaks following mock usage #15435

alexey-kozlenkov opened this issue Dec 31, 2024 · 1 comment

Comments

@alexey-kozlenkov
Copy link

alexey-kozlenkov commented Dec 31, 2024

Version

29.7.0

Steps to reproduce

  1. You write test for function A that calls function B.
  2. You want to mock function B for all but one test case
  3. You use jest.spy(bModule, 'B').mockImplementation(...) by default
  4. In that one specific test case you use spy.mockRestore() to get real implementation
  5. Boom! All subsequent test cases fail to use mocked implementation or re-mock it. mockRestore() restored it real hard.

Reproducible case:
https://codesandbox.io/p/sandbox/jest-mock-reset-breaks-future-kk4kjr

  1. Open link
  2. Run tests

Expected behavior

Able to turn spy to mock implementation in subsequent test cases after test case with mockRestore()

Actual behavior

Unable to get re-mock spy

Additional context

No response

@alexey-kozlenkov
Copy link
Author

Ok, I found out that re-creating spy itself after calling .mockRestore() helps. e.g.

  test("calls real sum", () => {
    sumSpy.mockRestore();

    expect(callSum(1, 2)).toBe(3);

    sumSpy = jest.spyOn(sumModule, "sum").mockImplementation(() => 5);
  });

I wonder if this is an expected behaviour or is there a way to keep the spy reference "alive" so that it could be re-mocked without being re-created?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant