Make Vitest `stubEnv()` work with SvelkeKit `$env/dynamic/public|private`
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 20.8k
- Forks
- 2.3k
- Avg merge
- 1d 16h
- Merged PRs (30d)
- 156
Description
Describe the problem
As developer I want to stub dynamic env-variables in my Vitest tests, so I can test the app with different env-settings.
https://vitest.dev/api/vi.html#vi-stubenv
Example
.env
FOO=bar
src/lib/config.ts
import { env } from '$env/dynamic/private';
export function getConfig() {
return env.FOO;
}
src/lib/config.test.ts
import { vi, describe, it, expect } from 'vitest';
import { getConfig } from './config';
describe('getConfig test', () => {
it('it gets config', () => {
vi.stubEnv('FOO', 'stub');
console.debug(process.env.FOO);
const config = getConfig();
expect(config).toBe('stub');
vi.unstubAllEnvs();
});
}
This example is currently not working.
Describe the proposed solution
Currently env-values are copied when the server starts:
Because of this, changing process.env-variables after the server has started will not change the env-values used in the SvelteKit app.
Instead of copying env-values, they could be retrieved via proxy (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) directly from process.env.
The proxy can then decide if the env-variable should be available (public vs. private).
Alternatives considered
Maybe it is possible to stub env-variables before the server starts.
Importance
would make my life easier
Additional Information
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading packages/kit/src/runtime/server/index.js around the linked environment-value copying at lines 31–32, then trace how $env/dynamic/public and $env/dynamic/private expose those values. Done means the provided Vitest stubEnv example observes the stubbed value while public and private availability rules remain correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100