-
Notifications
You must be signed in to change notification settings - Fork 6
Description
Bug Report Checklist
- I have tried restarting my IDE and the issue persists.
- I have pulled the latest
mainbranch of the repository. - I have searched for related issues and found none that matched my issue.
Expected
CFT's Vitest spies should play nicely with Vitest 3 and Vitest 4 tests. They shouldn't interfere with how folks do things in tests.
Actual
Right now, CFT's Vitest spy factory uses vi.spyOn to stub out methods of the container:
console-fail-test/src/spies/vitest.ts
Lines 28 to 37 in a1209e4
| const createVitestSpyFactory = (spyLibrary: Vitest): SpyFactory => { | |
| return (container: any, methodName: string) => { | |
| const spy = spyLibrary.vi.spyOn(container, methodName); | |
| return { | |
| getCalls: () => spy.mock.calls, | |
| restore: spy.mockRestore, | |
| }; | |
| }; | |
| }; |
This was all fine and good in Vitest 3. But in Vitest 4, https://vitest.dev/guide/migration.html#changes-to-mocking:
Calling
vi.spyOnon a mock now returns the same mock
That means that if a userland test calls vi.spyOn(console, "log"):
- In Vitest 3, they'd get a brand new mock
- In Vitest 4, they'll get the same mock as what CFT set
That's bad because if their unit test calls that mock, CFT will think those calls were calls to the global console!
I think CFT will have to go with a strategy like:
- In setup:
const originalMethod = container[methodName]andcontainer[methodName] = vi.fn() - In teardown:
container[methodName] = originalMethod
That way userland vi.spyOns will produce new mocks, not the same one.
Additional Info
I think this is a little unfortunate. I like how Vitest's spyOn handles changing the original object non-destructively for us. In this new Vitest 4 compatible approach, we might hit edge cases from the difference between assigning to the console instance vs. moving things back to the Console prototype. Those should be pretty rare edge cases that we can deal with if reported.
Tracked in CTA as: JoshuaKGoldberg/create-typescript-app#2305