Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vi.mock not working in browser mode with test files outside of root #7595

Open
6 tasks done
miguel-leon opened this issue Mar 2, 2025 · 15 comments
Open
6 tasks done
Labels
feat: browser Issues and PRs related to the browser runner p3-minor-bug An edge case that only affects very specific usage (priority)

Comments

@miguel-leon
Copy link

Describe the bug

I read it was implemented, but I can't get it to work. It works as expected when run in node though.

Is there a special configuration required that I haven't found in the docs?

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-pywprx8q?file=vite.config.ts

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/browser: latest => 3.0.7 
    @vitest/ui: latest => 3.0.7 
    playwright: latest => 1.50.1 
    vite: latest => 6.2.0 
    vitest: latest => 3.0.7 
    webdriverio: latest => 9.10.1

Used Package Manager

npm

Validations

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Mar 2, 2025

Did you try locally instead of stackblitz? Probably it won't work on stackblitz because of service worker or maybe for other reasons.

@miguel-leon
Copy link
Author

Yes, of course. I tried so many things in my local. stackblitz is a minimal reproduction I just created.

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Mar 2, 2025

I tried your repro locally and it's working for me, for example with playwright/chromium

export default defineConfig({
  test: {
    browser: {
      provider: 'playwright',
      // provider: 'webdriverio',
      enabled: true,
      instances: [
        { browser: 'chromium' },
        // { browser: 'chrome' },
      ],
    },
  },
});
$ pnpm test

> @vitest/example-test@ test /home/hiroshi/Downloads/vitest-dev-vitest-pywprx8q
> vitest


 DEV  v3.0.7 /home/hiroshi/Downloads/vitest-dev-vitest-pywprx8q

 ✓  chromium  test/basic.test.ts (1 test) 1ms
   ✓ basic mock

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  13:54:52
   Duration  1.49s (transform 0ms, setup 0ms, collect 137ms, tests 1ms, environment 0ms, prepare 214ms)

@miguel-leon
Copy link
Author

mmm I see, welp if the config is correct and it is supposed to work locally, I'll try to create another minimal repro in my local from scratch, since it does not work in my project.
Perhaps it's a Windows thing.

@miguel-leon
Copy link
Author

I found out when it's not working.

I had in my project's vite config values for root and test.include, I updated the repro, sorry.

export default defineConfig({
  root: './src',
  test: {
    include: ['../test/**/*.test.ts'],
    browser: {
      provider: 'playwright',
      // provider: 'webdriverio',
      enabled: true,
      instances: [
        { browser: 'chromium' },
        // { browser: 'chrome' },
      ],
    },
  },
});

Is that a bad configuration on my part? or is it still supposed to work like that?

I can't remember why I have it configured like that... maybe it needed root for something else, or perhaps it is a stale config from an old version.

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Mar 2, 2025

I'm not sure if there's a reason mock cannot work with this setup. I'll treat it as a bug for now.

@hi-ogawa hi-ogawa added p3-minor-bug An edge case that only affects very specific usage (priority) and removed pending triage labels Mar 2, 2025
@hi-ogawa hi-ogawa changed the title vi.mock not working in browser mode vi.mock not working in browser mode with test files outside of root Mar 2, 2025
@hi-ogawa hi-ogawa added the feat: browser Issues and PRs related to the browser runner label Mar 3, 2025
@bteng22
Copy link

bteng22 commented Mar 25, 2025

👋 Running into the same issue here on our project. Our app is a monorepo using npm workspaces so we run tests against each of our teams packages. root gets set to the working directory of each package. Any files outside of the root aren't able to be mocked while anything under root can be. This isn't ideal since a lot of our shared dependencies live outside of the team packages

@hi-ogawa do you have any ideas for workaround here until this gets patched?

@hi-ogawa
Copy link
Contributor

@bteng22 Can you provide a repro just in case? Potentially you also happen to hit #7708, which has some workaround.

@bteng22
Copy link

bteng22 commented Mar 28, 2025

👋 @hi-ogawa Here's a really simplified repro https://github.com/bteng22/nx-vitest-monorepo I wasn't able to build it on stackblitz since the NX Daemon had issues on it.

When you run npm test you'll see that package-b tests are failing because it's not able to mock modules from package-a. If we set the Vitest config's root to the project directory then it resolves the mock issues but then causes a lot of our tests to only fail on CI with errors like TypeError: Failed to fetch dynamically imported module

Is there any workarounds you can suggest here? This one been a big blocker for a lot of work on our team! Thanks for your help.

@bteng22
Copy link

bteng22 commented Mar 31, 2025

Tagging @sheremet-va as well to escalate this! Our project is in the middle of a migration from Jest to Vitest and we're completely blocked at the moment. Any guidance here would be really helpful. Thank you!

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Apr 1, 2025

Thanks for the repro. I took a look and that's slightly different condition than OP's repro, but I assume the cause is same.
OP's case is that test files are outside of root but mocked files are inside. In your case, it's opposite as test files are inside root, but mocked files are outside.

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Apr 1, 2025

@bteng22 Hmm, I just tested the latest Vitest 3.1.0 and it looks working now. Can you test it?

(Tested the OP's repro with the latest and that one seems still broken).

@arkadiy93
Copy link

@hi-ogawa

const mocks = vi.hoisted(() => {
  return {
    useSearch: vi.fn(),
  };
});

vi.mock('src/hooks/useSearch', () => {
  return {
    useSearch: mocks.useSearch,
  };
});

I have also issue with this setup. After going to 3.1.0 it started working when I run my test file individually.
But when I run vitest run command and all test files run then this test fails with error:
Vitest failed to find the runner. This is a bug in Vitest. Please, open an issue with reproduction.

@bteng22
Copy link

bteng22 commented Apr 1, 2025

@hi-ogawa Hmm still not working for me 😞 Here's the commit to update to 3.1.0 I also tried the latest 3.1.1: bteng22/nx-vitest-monorepo@3539f06. Any chance you're able to create a PR or fork the repo and push up what you had to get it working?

The add function below is still the original and not a Vitest spy.

❯ npm test

> [email protected] test
> nx run-many --target=test --all --skip-nx-cache


   ✔  nx run @ui/package-c:test (1s)
   ✔  nx run @ui/package-a:test (1s)

—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
   ✖  nx run @ui/package-b:test
      > @ui/[email protected] test
      > vitest run --config ../../../vitest.config.ts
      
      
       RUN  v3.0.5 /Users/bteng22/_REPOS/nx-vitest-monorepo/ui/packages/package-b
      
      stdout | __tests__/index.test.ts > multiplies two numbers correctly using mocked add
      ??add [Function add]
       ❯  browser (chromium)  __tests__/index.test.ts (1 test | 1 failed) 3ms
         × multiplies two numbers correctly using mocked add 2ms
           → add.mockImplementation is not a function
      
      ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
      
       FAIL   browser (chromium)  __tests__/index.test.ts > multiplies two numbers correctly using mocked add
      TypeError: add.mockImplementation is not a function
       ❯ __tests__/index.test.ts:11:23
            9| 
           10| test('multiplies two numbers correctly using mocked add', () => {
           11|   console.log('??add', add);
             |                       ^
           12|   (add as Mock).mockImplementation((...args: number[]) => args.reduce(…
           13| 
      
      ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
      
      
       Test Files  1 failed (1)
            Tests  1 failed (1)
         Start at  07:40:21
         Duration  694ms (transform 0ms, setup 0ms, collect 101ms, tests 3ms, environment 0ms, prepare 133ms)
      
      npm error Lifecycle script `test` failed with error:
      npm error code 1
      npm error path /Users/bteng22/_REPOS/nx-vitest-monorepo/ui/packages/package-b
      npm error workspace @ui/[email protected]
      npm error location /Users/bteng22/_REPOS/nx-vitest-monorepo/ui/packages/package-b
      npm error command failed
      npm error command sh -c vitest run --config ../../../vitest.config.ts
      
      

—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

 NX   Ran target test for 3 projects (3s)

   ✔  2/3 succeeded [0 read from cache]

   ✖  1/3 targets failed, including the following:

      - nx run @ui/package-b:test

@hi-ogawa
Copy link
Contributor

hi-ogawa commented Apr 2, 2025

@arkadiy93 Please provide a reproduction for us to take a look (just like error said) 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat: browser Issues and PRs related to the browser runner p3-minor-bug An edge case that only affects very specific usage (priority)
Projects
None yet
Development

No branches or pull requests

4 participants