tom*_*zub 9 jsdom typescript reactjs vite vitest
我在 Vite/React/TypeScript 应用程序中,正在使用 Vitest 配置我的第一个测试。
当我运行 Button 测试 (yarn vitest) 时,出现以下错误:
packages/frontend/src/components/Generic/Button/Button.test.tsx > Button > should render the button
ReferenceError: document is not defined
Run Code Online (Sandbox Code Playgroud)
据我所知,Vitest 不能与 JSDom 一起使用。我尝试过几件事:
我更喜欢使用第一个选项(使用 vite.config.ts)来仅共享一个配置。是否可以 ?
注 1:我已经安装的 JSdom 有“devDependency”。注 2:要使用 vitest.config.ts,我应该像这样更新 package.json 中的脚本:
"test": "vitest --config ./packages/frontend/vitest.config.ts"
这是我的文件:
// 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'],
},
})
Run Code Online (Sandbox Code Playgroud)
我尝试添加这样的 vitest.config.ts :
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['*.ts', '*.tsx'], // FIXME
environment: 'jsdom',
},
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5050 次 |
| 最近记录: |