Repository navigation
Description
Describe the bug
Could maybe be related to #7871 .
We are beginning to see a lot of flakiness in our test suite. Particularly with two types of issues and I am wondering if we are doing something fundamentally wrong. Here are the two cases.
First case
We sometimes get TypeError: [Function ...] is not a spy or a call to a spy! when they are properly set as spies.
This is one of the test file that failed with this :
TypeError: [Function createBaseStore] is not a spy or a call to a spy!
Failure screenshot:
- src/components/commerce/atomic-commerce-recommendation-interface/__screenshots__/store.spec.ts/-createCommerceRecommendationStore-should-call--createBaseStore-with-the-correct-arguments-1.png
❯ src/components/commerce/atomic-commerce-recommendation-interface/store.spec.ts:23:28
21| it('should call #createBaseStore with the correct arguments', () => {
22| expect(store).toBeDefined();
23| expect(createBaseStore).toHaveBeenCalledExactlyOnceWith({
| ^
24| loadingFlags: [],
25| iconAssetsPath: '',
This is the specific test file : https://github.com/coveo/ui-kit/blob/master/packages/atomic/src/components/commerce/atomic-commerce-recommendation-interface/store.spec.ts
Are we doing something wrong with this test or is there a problematic race condition somewhere ?
Second case
We sometimes get vi.mocked(...).mockReturnValue is not a function.
This error often gets triggered for the whole suite as if the test is ran before the global mocks.
× atomic-commerce-load-more-products > when interface element type is 'product-listing' > should call #buildProductListing with engine 264ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when interface element type is 'product-listing' > should initialize pagination controller from product listing 244ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when interface element type is 'search' > should call #buildSearch with engine 191ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when interface element type is 'search' > should initialize pagination controller from search 182ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > should render nothing when the app is not loaded 278ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > should render nothing when there are no products 117ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > should render the container 190ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > should render a localized summary with formatted numbers 168ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > should render a progress bar with the correct width 214ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > should not render a load more button when all products are loaded 182ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > should render a load more button with the correct localized label when more products are available 298ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > when the load more button is clicked > should call #fetchMoreProducts 165ms
→ vi.mocked(...).mockReturnValue is not a function
× atomic-commerce-load-more-products > when the app is loaded and there are products > when the load more button is clicked > should call #focusOnNextNewResult 362ms
→ vi.mocked(...).mockReturnValue is not a function
This is an example of one test that failed
TypeError: vi.mocked(...).mockReturnValue is not a function
Failure screenshots:
- src/components/commerce/atomic-commerce-load-more-products/__screenshots__/atomic-commerce-load-more-products.spec.ts/atomic-commerce-load-more-products-when-interface-element-type-is--product-listing--should-call--buildProductListing-with-engine-1.png
- src/components/commerce/atomic-commerce-load-more-products/__screenshots__/atomic-commerce-load-more-products.spec.ts/atomic-commerce-load-more-products-when-interface-element-type-is--product-listing--should-initialize-pagination-controller-from-product-listing-1.png
❯ renderLoadMoreProducts src/components/commerce/atomic-commerce-load-more-products/atomic-commerce-load-more-products.spec.ts:53:37
51|
52| if (interfaceType === 'product-listing') {
53| vi.mocked(buildProductListing).mockReturnValue(
| ^
54| buildFakeProductListing({
55| state: {
Again this is the test file : https://github.com/coveo/ui-kit/blob/master/packages/atomic/src/components/commerce/atomic-commerce-load-more-products/atomic-commerce-load-more-products.spec.ts
Are we doing something wrong here again ?
Thank you !
Reproduction
I don't have a proper reproduction case since this seem to be random and flaky but here is our config.
https://github.com/coveo/ui-kit/blob/master/packages/atomic/vitest.config.ts
System Info
System:
OS: macOS 15.5
CPU: (12) arm64 Apple M3 Pro
Memory: 297.77 MB / 36.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 22.14.0 - ~/.nvm/versions/node/v22.14.0/bin/node
npm: 11.4.2 - ~/.nvm/versions/node/v22.14.0/bin/npm
Browsers:
Chrome: 138.0.7204.159
Chrome Canary: 140.0.7314.0
Safari: 18.5
npmPackages:
@vitest/browser: 3.2.4 => 3.2.4
playwright: 1.54.1 => 1.54.1
vitest: 3.2.4 => 3.2.4Used Package Manager
npm
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
Activity
todor-a commentedon Oct 13, 2025
I've noticed it's not only on CI - when I run the tests locally, with browser mode on and with watch, it always errors with this on the first rerun and I have to restart them.
The biggest issue is that you cannot debug tests in the browser mode UI since the second run always fails with this error...
Another case that I've noticed is that when I run a suite on its own, it's fine, but when I run a few suites together, they somehow interfere with each other and this errors.
louis-bompart commentedon Nov 10, 2025
👋 We want to give a status update regarding this issue.
We think this flakiness is explained here #8849, specifically by this bit:
We fixed our issue by "hoisting" the
vi.mock(moduleSpecifier, {spy: true})of the module in our setupFiles.FedericoGarciaGarcia commentedon Apr 13, 2026
Having the same issue only in CI (never happens locally):
It's random. It happens in both Vitest 3 and 4. Out of dozens of test files only one fails. The failed test file is not always the same. I'm wondering if setting
fileParallelismtofalsemight solve this until the bug is fixed? Maybe parallel test runs are conflicting with one another?Update: I ran it in a docker container locally and it happened.
iansan5653 commentedon Apr 13, 2026
We are also seeing this intermittently. One file will fail with the
vi.mocked(...).mockResolvedValue is not a functionerror while the rest of CI (hundreds of other test files) will pass fine. It doesn't happen in most CI runs; maybe one in ten (a very rough estimate).FedericoGarciaGarcia commentedon Apr 14, 2026
I was able to make a reproduction. I forked the repo and made a branch to test it: https://github.com/FedericoGarciaGarcia/vitest/tree/docker
The branch works like this:
Here's how to run it:
Screenshot of the error. 3 out of 5 runs failed.
FedericoGarciaGarcia commentedon Apr 14, 2026
I also ran this in a terminal, outside of docker, and after over 20 runs none of them have failed, so I have to assume the issue is only in docker and for
chromium.firefoxandwebkitdon't fail.FedericoGarciaGarcia commentedon Apr 14, 2026
I added a
console.logto eachvi.mockcall to check if they are actually being called, like this:And it wasn't called for the test file that had the error.
Venosta-web commentedon Jul 7, 2026
Measured datapoints from a production suite that hits this, in case they help narrow it down (vitest 4.1.8, browser mode via
@vitest/browser-playwright, real Chromium, ~330 test files, 111 of them using hoistedvi.mock):vitest run --retry=0 --coverage.enabled=false, GitHub Actions ubuntu-latest). We measured it with a workflow that runs the suite 10× in a parallel matrix.vi.mockfactories were never registered — every test in the file fails withvi.mocked(...).mockResolvedValueOnce is not a function/[Function ...] is not a spy, and stack traces show the real module executing (e.g. real three.jsMeshconstructor when the file mocks'three'). Across 5 observed incidents the victim file was different each time (a three.js-mocking spec twice, two different nanostores slice specs, etc.); mocked targets include bothnode_modulespackages and local modules, so it doesn't look optimizer-specific.retrydoes not recover: withretry: 2, the same assertions fail identically on all 3 attempts — consistent with the file's module graph being poisoned for its whole lifetime rather than a per-test race.vitest runstep (or the CI job) has never reproduced the failure twice in a row. We now absorb it in CI by re-running the step once on failure.fileParallelism/isolateoverrides),setupFiles, Playwright provider, chromium instance.Happy to run diagnostic builds or add instrumentation to the flake-hunter workflow if that's useful — with a 20% hit rate per 10-run batch we can get signal on a candidate fix within ~an hour.
Stwissel commentedon Aug 19, 2026
Still present on vitest 4.1.11 (
@vitest/browser-playwright, Chromium, headless,browser.instances: [{ browser: 'chromium' }], Ubuntu GitHub-hosted runner). Adding data in case it helps triage — I have no minimal reproduction, and I'll explain why below.Signature
Exactly the two symptoms in this issue, and they co-occur in one file:
The failing file's
vi.mock(...)simply never took effect — the real module was linked. Everything else in the same run passes.What it is not (measured, not assumed)
vi.mockprecedes all imports and files where it follows one.Useful tell
The affected file's runtime explodes: 1299ms vs 9ms for the same 24 tests. That is consistent with real network calls replacing mocked ones, and it is a cheap signal to key on if you want telemetry from the wild.
Why there's no minimal reproduction
It is load-dependent, not code-dependent. 9/9 guaranteed-cold full-suite runs (93 files, 1493 tests, fresh
cacheDireach time) passed on an idle macOS machine. It only appears on loaded CI runners, at roughly 1 run in 5, on a suite whose files import heavy web-component libraries.Where I'd look
ModuleMockerServerInterceptor.register()is an out-of-process RPC:So mock registration and module import are two processes racing over a websocket, and the server rewrites the module response from a registry the browser populated asynchronously. That shape would produce exactly this — silently serving the real module when the import wins — and it would be load-sensitive and file-arbitrary, which matches every observation above. Note also that
rpc()rejects after 5s; under heavy parallelism I'd want to know whether that rejection can be swallowed anywhere, since a lost registration fails open (real module) rather than closed (error).Happy to run instrumented builds against this if a maintainer wants specific data — I have a suite that reproduces it in CI at a usable rate.
fatih-acar commentedon Aug 21, 2026
We hit this in CI (~1 in 30-100 runs) and root-caused it with instrumentation. Root cause:
a race between Playwright's request-interception activation and the first module fetch
after mock registration.
TL;DR
The
@vitest/browser-playwrightprovider servesvi.mockviacontext.route()andunroutes everything when a test file finishes. Routes therefore drop to zero between test
files, so Chromium's
Fetchinterception is disabled and re-enabled around every testfile that uses mocks. Playwright awaits the CDP
Fetch.enableack, but Chromium appliesinterception asynchronously after that ack — so a module request issued within ~1ms of
context.route()resolving can slip past the route and load the real module. The ESmodule registry then caches the real namespace for the file's lifetime, which produces
exactly the reported signature: every test in one random file fails with
vi.mocked(...).mockX is not a function/[Function ...] is not a spy, retries don'trecover, a fresh run does.
Evidence
vitest 4.1.10,
@vitest/browser-playwright4.1.10, playwright 1.60.0, chromium headless,Linux. We instrumented the provider mocker (
register/clear/route-handler hits) plus aVite middleware logging every module request, and stress-looped a 5-file subset of our
suite: 6 failing runs out of 30. All six show the identical trace:
The mocked module's plain URL reaches the Vite server 0-1ms after the fully-awaited
route registration. Registrations whose first fetch lands ≥5ms later always intercept.
Client-side ordering is correct (
prepare()is awaited before the rewritten imports run),and the registration rpc is the session-scoped birpc
registerMockwithtimeout: -1—not the
hot.sendinterceptor suspected above (that path is only used by the standalonemockerPlugin, not this provider). Registration completes; activation lags.This also explains the observations in this thread:
Fetch.enableinCRNetworkManager; Firefox/WebKituse different backends),
fast first fetch after registration both widen the odds),
retryuseless,Fix suggestion
Don't let the route count cross 0↔1 per test file: keep interception enabled for the whole
session, e.g. install a permanent never-matching route when the provider creates a context:
Per-file mock registration then becomes a pure matcher-list update in the Playwright
server, which is atomic w.r.t. the next
Fetch.requestPaused— no activation window.Validated on our suite: 6/30 runs corrupted without the anchor route, 74/74 clean with
it (40 via a patched provider, 34 via the config-level wrapper below). Trade-off:
interception stays active for unmocked files too; our 180-file suite went from ~28s to
~43s wall locally with 32 parallel sessions (CI with fewer sessions should see less).
Workaround for affected users (vitest 4.1.x)
Happy to share the instrumentation diff or run diagnostic builds — the 5-file stress loop
reproduces at ~20% per run, so a candidate fix gets signal in minutes.
test(frontend): keep playwright interception always on so vi.mock can…
test(frontend): keep playwright interception always on so vi.mock can…
test: hold browser interception on so a mock cannot be lost
greedyivan commentedon Aug 28, 2026
@cplieger Thank you for carrying this diagnosis into production — much appreciated. For the record: PR #11055 (the same fix) was closed automatically by an anti-slop moderation bot, not by the author or maintainers, and never got a review. Would you consider opening a PR upstream? Your independent validation would have a good chance of moving this out of triage.
cplieger commentedon Aug 28, 2026
done
test: drop the interception wrapper and widen the Stryker dry-run budget
silverwind commentedon Sep 26, 2026
Hitting this quite often, for example https://github.com/go-gitea/gitea/actions/runs/36142223848/job/108095578632. Feel free to use as a possible reproduction. It's rare but eventually it will happen.
fix(browser): close the mock route interception race (fix #8339) (#11083
test: verify Chromium interception before browser mocks apply (#1675)
docs: note the vitest 5.0.3 browser mock race