I'm using an env variable MY_VAR
that I use from $env/static/public
import { MY_VAR } from '$env/static/public';
export const myVar = MY_VAR === 'true';
I'd like to mock it in some tests, to support the 2 scenarios: MY_VAR
build true
/ false
. But I cannot manage to do it. I'm using vitest.
I tried setting up a mock file __mock__/env/static/public.ts
with :
export const MY_VAR = 'false';
with vitest.config.ts
:
export default defineConfig(({ mode }) => ({
// ...
resolve: {
alias: {
'$env/static/public': path.resolve(__dirname, '__mocks__/env/static/public')
}
}
}));
I also tried some combination of vi.mock
, vi.hoisted
, vi.spyOn
but I couldn't manage to make it work.
How can I mock $env/static/public
with vitest?
vi.mock()
should work fine:
vi.mock('$env/static/public', () => {
return Promise.resolve({
MY_VAR: 'mock value'
});
});
You put this at the top, although I think these mockings are always hoisted, so maybe the position doesn't matter.