How do I get variables defined in my setup files to work in my test files?
Setup files:
var lol = 'lol'
test:
describe("test", () => {
it("test lol", () => {
expect(lol).toBe("lol");
});
});
This does not work as expected. However
window.lol = 'lol'
This works. Is there any way to get the former version to work or automatically set all global variables to be properties of window?
If you check out the vitetest test suites:
https://github.com/vitest-dev/vitest/tree/main/test/global-setup
You'll see an example where they use the setupFiles
in the test
config to specifically attach values to global
(specifically with the beforeAll
hook); note that each tests suite uses its own context which is why it is done this way (as opposed to through the globalSetup
field of the config).
For example to add lol
:
// vite.config.js
export default defineConfig({
test: {
// ...
setupFiles: ['./src/utils/setup-teardown-hooks.js'],
// ...
},
});
And then:
// setup-teardown-hook.js
import { afterAll, beforeAll } from 'vitest';
beforeAll(() => {
global.lol = '🥳';
});
afterAll(() => {
delete global.lol
});
Edit: It looks like alternatively you can also use the populateGlobal
utility function through Vitest - Custom Environment :
Vitest also provides populateGlobal utility function, which can be used to move properties from object into the global namespace: