I'm in a Vite/React/TypeScript application and I'm configuring my first test with Vitest.
When I run my Button test (yarn vitest), I get this error:
packages/frontend/src/components/Generic/Button/Button.test.tsx > Button > should render the button
ReferenceError: document is not defined
I understand that Vitest does not work with JSDom. I have tried several things:
- KO: Specifying in the vite.config.ts file to use JSDom
- OK: Adding a vitest.config.ts file specifying to use JSDom
- OK: Adding an annotation (@vitest-environment jsdom) at the top of the test file
I would prefere use the first option (use vite.config.ts) to share only one configuration. Is it possible ?
Note 1 : JSdom i already installed has "devDependencies".
Note 2 : to use vitest.config.ts i should update the script in package.json like that :
"test": "vitest --config ./packages/frontend/vitest.config.ts"
Here are my files:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import viteTsConfigPaths from 'vite-tsconfig-paths'
import tailwindcss from 'tailwindcss'
export default defineConfig({
server: {
port: 4200,
host: 'localhost',
},
rollupOption: {
external: ['@internals/components/index']
},
define: {
global: {},
},
plugins: [
react(),
tailwindcss(),
viteTsConfigPaths({
root: '../../',
}),
],
resolve: {
alias: {
// runtimeConfig is a special alias that is used to import the correct config file
'./runtimeConfig': './runtimeConfig.browser',
// public alias
'@publics': `${__dirname}/public`,
// only internals (private) aliases are allowed here
'@internals/components': `${__dirname}/src/components`,
'@internals/features': `${__dirname}/src/features`,
'@internals/hooks': `${__dirname}/src/hooks`,
'@internals/models': `${__dirname}/src/models`,
'@internals/utils': `${__dirname}/src/utils`,
'@internals/types': `${__dirname}/src/types`,
'@internals/styles': `${__dirname}/src/styles`,
'@internals/assets': `${__dirname}/src/assets`,
'@internals/store': `${__dirname}/src/store`,
'@internals/config': `${__dirname}/src/config`,
'@internals/services': `${__dirname}/src/services`,
},
},
test: {
globals: true,
cache: {
dir: '../../node_modules/.vitest',
},
environment: 'jsdom',
include: ['*.tsx', '*.ts', '*.jsx', '*.js'],
},
})
I tried to add a like this vitest.config.ts :
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['*.ts', '*.tsx'], // FIXME
environment: 'jsdom',
},
})
npx vitest
and it didn't find jsdom because of that. Running in a script from the package.json worked (npm run test
). – Nipa