Skip to content

[Browser] Inexplicable flakiness with spies and mocks in CI #8339

Closed

Description

@alexprudhomme

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.4

Used Package Manager

npm

Validations

Activity

  1. todor-a commented on Oct 13, 2025

    @todor-a
    Contributor

    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.

  2. louis-bompart commented on Nov 10, 2025

    @louis-bompart

    👋 We want to give a status update regarding this issue.
    We think this flakiness is explained here #8849, specifically by this bit:

    how previous tests can influence wether vi.mock('./module.js', { spy: true }) no longer works because that module was imported without mocks before

    We fixed our issue by "hoisting" the vi.mock(moduleSpecifier, {spy: true}) of the module in our setupFiles.

  3. FedericoGarciaGarcia commented on Apr 13, 2026

    @FedericoGarciaGarcia

    Having the same issue only in CI (never happens locally):

    Error: TypeError: vi.mocked(...).mockResolvedValue is not a function
    

    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 fileParallelism to false might 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.

  4. iansan5653 commented on Apr 13, 2026

    @iansan5653

    We are also seeing this intermittently. One file will fail with the vi.mocked(...).mockResolvedValue is not a function error 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).

  5. FedericoGarciaGarcia commented on Apr 14, 2026

    @FedericoGarciaGarcia

    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:

    • Creates a docker container
    • Adds a test with a simple calculator UI. It mocks math functions and interacts with the UI to show a result
    • Docker copies the test file hundreds of times and runs them in parallel in a loop endlessly for each browser: firefox, safari, chromium
    • After a while it should error out

    Here's how to run it:

    1. Build the image
    docker compose build browser-tests
    
    1. Run 500 test files in parallel, each test file has 3 tests
    TEST_COPIES=500 docker compose run browser-tests
    

    Screenshot of the error. 3 out of 5 runs failed.

    Screenshot 2026-04-14 at 11 05 48
  6. FedericoGarciaGarcia commented on Apr 14, 2026

    @FedericoGarciaGarcia

    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. firefox and webkit don't fail.

  7. FedericoGarciaGarcia commented on Apr 14, 2026

    @FedericoGarciaGarcia

    I added a console.log to each vi.mock call to check if they are actually being called, like this:

    vi.mock('../src/math1', () => {
      console.log('mocking math1');
      return { ... }
    });

    And it wasn't called for the test file that had the error.

  8. Venosta-web commented on Jul 7, 2026

    @Venosta-web

    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 hoisted vi.mock):

    • Reproduction rate: 2/10 full-suite runs (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.
    • Symptom: in a failing run, one seemingly random module-mocking file behaves as if its hoisted vi.mock factories were never registered — every test in the file fails with vi.mocked(...).mockResolvedValueOnce is not a function / [Function ...] is not a spy, and stack traces show the real module executing (e.g. real three.js Mesh constructor 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 both node_modules packages and local modules, so it doesn't look optimizer-specific.
    • Per-test retry does not recover: with retry: 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.
    • A fresh vitest process always recovers: re-running the whole vitest run step (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.
    • Config: default isolation/parallelism (no fileParallelism/isolate overrides), 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.

  9. Stwissel commented on Aug 19, 2026

    @Stwissel

    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:

    TypeError: fetchBackendVersion.mockReturnValue is not a function
    TypeError: [AsyncFunction tdFetch] is not a spy or a call to a spy!
    

    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)

    • Not the dep optimizer. I had attributed it to mid-run on-demand optimization reloading the iframe. Wrong: cold and warm optimizer runs produce an identical dep set (760 entries) and Vite logs "using post-scan optimizer result, the scanner found every used dependency". No re-optimize occurs in the failing runs.
    • Not partial mock factories. One failing file's factory covers every runtime export of the mocked module.
    • Not source order. It hits files where vi.mock precedes all imports and files where it follows one.
    • Not file-specific. Four different files have been hit over ~3 weeks; the affected file is arbitrary and is never one the change touched.

    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 cacheDir each 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:

    // @vitest/mocker/dist/chunk-interceptor-native.js
    async register(module) { await rpc('vitest:interceptor:register', module.toJSON()) }
    // chunk-mocker.js — rpc() is hot.send + a 5s reject timeout over the Vite WS

    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.

  10. fatih-acar commented on Aug 21, 2026

    @fatih-acar

    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-playwright provider serves vi.mock via context.route() and
    unroutes everything when a test file finishes. Routes therefore drop to zero between test
    files, so Chromium's Fetch interception is disabled and re-enabled around every test
    file that uses mocks
    . Playwright awaits the CDP Fetch.enable ack, but Chromium applies
    interception 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 ES
    module 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't
    recover, a fresh run does.

    Evidence

    vitest 4.1.10, @vitest/browser-playwright 4.1.10, playwright 1.60.0, chromium headless,
    Linux. We instrumented the provider mocker (register/clear/route-handler hits) plus a
    Vite 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:

    t=1035  register.done   session=a292f4  /src/.../get-branch-task-status-from-api.ts   # context.route() resolved, rpc acked
    t=1036  http (plain)    /src/.../get-branch-task-status-from-api.ts                   # plain URL reaches Vite — NOT intercepted
            (this session never gets a single route hit)
    

    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 registerMock with timeout: -1 —
    not the hot.send interceptor suspected above (that path is only used by the standalone
    mockerPlugin, not this provider). Registration completes; activation lags.

    This also explains the observations in this thread:

    • chromium-only (the enable path is Fetch.enable in CRNetworkManager; Firefox/WebKit
      use different backends),
    • load-dependent with no minimal repro (the window is ~1ms; contended CI runners and a
      fast first fetch after registration both widen the odds),
    • random victim file, whole file poisoned, per-test retry useless,
    • "runtime explodes" for the victim file (real network instead of mocks).

    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:

    await context.route(() => false, () => {});

    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)

    import { type PlaywrightBrowserProvider, playwright } from "@vitest/browser-playwright";
    
    function playwrightWithAlwaysOnInterception() {
      const provider = playwright();
      return {
        ...provider,
        providerFactory(...args: Parameters<typeof provider.providerFactory>) {
          const instance = provider.providerFactory(...args) as PlaywrightBrowserProvider;
          const anchored = new WeakSet<object>();
          const openPage = instance.openPage.bind(instance);
          instance.openPage = async (sessionId, url, options) => {
            await openPage(sessionId, url, options);
            const context = instance.contexts.get(sessionId);
            if (context && !anchored.has(context)) {
              anchored.add(context);
              await context.route(
                () => false,
                () => {}
              );
            }
          };
          return instance;
        },
      };
    }
    // vitest.config.ts: test.browser.provider = playwrightWithAlwaysOnInterception()

    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.

  11. greedyivan commented on Aug 28, 2026

    @greedyivan

    @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.

  12. cplieger commented on Aug 28, 2026

    @cplieger
    Contributor

    @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.

    done

  13. silverwind commented on Sep 26, 2026

    @silverwind
    Contributor

    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.

  14. added a commit that references this issue on Oct 1, 2026
    d6620fa
  15. locked and limited conversation to collaborators on Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions