🌐 AI搜索 & 代理 主页
Skip to content

🐛 Bug: Vitest 4 spyOn changes result in deduplicated console mocks #1059

@JoshuaKGoldberg

Description

@JoshuaKGoldberg

Bug Report Checklist

  • I have tried restarting my IDE and the issue persists.
  • I have pulled the latest main branch 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:

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.spyOn on 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] and container[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

Metadata

Metadata

Labels

status: accepting prsPlease, send a pull request to resolve this! 🙏type: bugSomething isn't working 🐛

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions