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

mockRestore doesn't restore spied on properties to their original values #3127

Closed
6 tasks done
kherock opened this issue Apr 3, 2023 · 2 comments · Fixed by #3386
Closed
6 tasks done

mockRestore doesn't restore spied on properties to their original values #3127

kherock opened this issue Apr 3, 2023 · 2 comments · Fixed by #3386

Comments

@kherock
Copy link

kherock commented Apr 3, 2023

Describe the bug

When using vi.spyOn() to create function mocks, the spy.mockRestore(), vi.mockRestoreAllMocks() doesn't actually restore the original descriptor of the spied-on object. This can lead to tests being written without ensuring that a method was already mocked, and deviates from Jest's equivalent behavior.

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-csdybj?file=test%2Fbasic.test.ts

test('should restore a spy', () => {
  const originalImpl = instance.fn1;
  const spy = vi.spyOn(instance, 'fn1');
  instance.fn1();
  spy.mockRestore();
  expect(instance.fn1).toEqual(originalImpl); // fails
});

test('should fail because it doesn\'t set up a spy', () => {
  instance.fn1();
  expect(instance.fn1).toHaveBeenCalledOnce(); // doesn't throw
});

System Info

System:
    OS: macOS 12.6.3
    CPU: (10) arm64 Apple M1 Pro
    Memory: 88.91 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.19.1 - ~/.local/share/homebrew/bin/node
    Yarn: 3.4.1 - ~/.local/share/homebrew/bin/yarn
    npm: 8.19.3 - ~/.local/share/homebrew/bin/npm
  Browsers:
    Firefox: 102.2.0
    Safari: 16.3

envinfo doesn't seem to work with my project's setup (Yarn 3 monorepo), here are my vitest versions:

    "vite": "^4.2.1",
    "vitest": "^0.29.8"

Used Package Manager

yarn

Validations

@sheremet-va
Copy link
Member

This is technically intended behavior. I am not sure if it's the right behavior, but removing a spy breaks module mocking as far as I remember. If someone has time to investigate the consequences of this change, be my guest.

@adrianbienias
Copy link

vi.restoreAllMocks docs says

Will call .mockRestore() on all spies. This will clear mock history and reset its implementation to the original one.

For me, it doesn't sound correct - spies aren't reset to the original state, they preserve the mocked one (which is not expected).

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

Successfully merging a pull request may close this issue.

3 participants