Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vitest global variables in setupfiles

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?

like image 937
Harry Avatar asked Jan 25 '26 23:01

Harry


1 Answers

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:

like image 134
Ashton Engberg Avatar answered Jan 28 '26 11:01

Ashton Engberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!