vitest icon indicating copy to clipboard operation
vitest copied to clipboard

import.meta.env.BASE_URL vite built-in constant breaks with vitest 4.x

Open Sheldoras opened this issue 3 months ago • 3 comments

Describe the bug

With vitest 4.x the vite built-in import.meta.env.BASE_URL no longer has the expected value set (base from the vite config as per docs).

For example if I have a component that displays the value of import.meta.env.BASE_URL doing a regular vite the value is displayed as expected.

If I now write a test with vitest 4.x that asserts for this value, the test breaks because the value is just / regardless of what is set in the base field of the vite config.

Reproduction

Small example project here

If you run vitest run with vitest version 4.0.6 for example, the one test asserting for the BASE_URL value will fail. If you switch the vitest version to a 3.x version 3.2.4 for example, all tests succeed.

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (24) x64 12th Gen Intel(R) Core(TM) i7-12850HX
    Memory: 28.41 GB / 63.61 GB
  Binaries:
    Node: 22.14.0 
    npm: 10.9.2 
    pnpm: 10.8.1 
  Browsers:
    Chrome: 141.0.7390.123
    Edge: Chromium (140.0.3485.54)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @vitejs/plugin-vue: ^6.0.1 => 6.0.1 
    vite: ^7.1.7 => 7.1.12 
    vitest: ^4.0.6 => 4.0.6

Used Package Manager

npm

Validations

Sheldoras avatar Oct 31 '25 15:10 Sheldoras

The problem seems to be deeper. We have the following setup in our vite config:

define: { 'import.meta.env.API_URL': JSON.stringify(apiUrl) },

where const apiUrl = process.env.API_URL || config.default_api_path;

And while this works in vitest 3, it seems to break in vitest 4 as import.meta.env.API_URL returns undefined in tests now when using browser mode.

SomaH123 avatar Nov 04 '25 09:11 SomaH123

The problem seems to be deeper. We have the following setup in our vite config:

I think your issue is related to https://github.com/vitest-dev/vitest/issues/8887

With vitest 4.x the vite built-in import.meta.env.BASE_URL no longer has the expected value set (base from the vite config as per docs).

This was a breaking change to make it easier to support the module runner. Can you explain why you need a custom base inside your tests? If you rely on its static value, why define it?

sheremet-va avatar Nov 27 '25 09:11 sheremet-va

I accidentally created a duplicate for this. For example the official Vue starter initializes Vue-Router with import.meta.env.BASE_URL, which is handy: your Vite base configuration is also used in the links created by the router. If you have a different base configuration in different environments, the solution works automatically.

I ran into the problem when UI component snapshot tests turned red because the router links were no longer including the expected base. I can't therefore confirm through a test that the router links are formed correctly.

ajuvonen avatar Dec 02 '25 14:12 ajuvonen