vitest icon indicating copy to clipboard operation
vitest copied to clipboard

isMockedFunction returns wrong value after object is spied on twice

Open kwojcik opened this issue 1 year ago • 1 comments

Describe the bug

Spy on an object twice and call restoreAllMocks, then isMockedFunction still thinks that it is a mock function.

Reproduction

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

import { describe, expect, it, vi } from "vitest";

const fooService = { foo: () => "foo" };
describe("fooService", () => {
  describe("foo", () => {
    it("is not a mock functon after 1 spy", () => {
      vi.spyOn(fooService, "foo").mockImplementation(() => "bar");
      vi.restoreAllMocks();
      expect(vi.isMockFunction(fooService.foo)).toBe(false);
    });
    it("it not a mock function after 2 spys", () => {
      vi.spyOn(fooService, "foo").mockImplementation(() => "bar");
      vi.spyOn(fooService, "foo").mockImplementation(() => "bar");
      vi.restoreAllMocks();
      expect(vi.isMockFunction(fooService.foo)).toBe(false);
    });
  });
});
 ❯ test/fooService.test.ts (2)
   ❯ fooService (2)
     ❯ foo (2)
       ✓ is not a mock functon after 1 spy
       × it not a mock function after 2 spys

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  test/fooService.test.ts > fooService > foo > it not a mock function after 2 spys
AssertionError: expected true to be false // Object.is equality

- Expected
+ Received

- false
+ true

 ❯ test/fooService.test.ts:15:49
     13|       vi.spyOn(fooService, "foo").mockImplementation(() => "bar");
     14|       vi.restoreAllMocks();
     15|       expect(vi.isMockFunction(fooService.foo)).toBe(false);
       |                                                 ^
     16|     });
     17|   });

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @vitest/ui: latest => 2.0.5 
    vite: latest => 5.4.2 
    vitest: latest => 2.0.5

Used Package Manager

npm

Validations

kwojcik avatar Aug 28 '24 18:08 kwojcik

I think it's a bug with https://github.com/tinylibs/tinyspy. It restores the previous property decorator, not the original one. Maybe if the property is already spied, we need to return the spy instead of reapplying the spy.

sheremet-va avatar Aug 29 '24 15:08 sheremet-va