Vitest 中的“描述未定义”

Mic*_*ant 6 javascript jsx jestjs vite vitest

我开始使用 Vite 开发 React 应用程序,但无法让笑话测试正常工作。我正在尝试将 Vitest 与实验性 ES 模块一起使用。

我正进入(状态:

FAIL  src/App.test.tsx [ src/App.test.tsx ]
ReferenceError: describe is not defined
Run Code Online (Sandbox Code Playgroud)

我添加了 Jest、Mocha Vite 和 Vitest,但没有帮助。

我的 package.json 有

  "devDependencies": {
    "@testing-library/react": "^14.0.0",
    "@types/jest": "^29.5.0",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "@vitejs/plugin-react-swc": "^3.0.0",
    "jest": "^29.5.0",
    "mocha": "^10.2.0",
    "typescript": "^4.9.3",
    "vite": "^4.2.0",
    "vitest": "^0.29.8"
  }
Run Code Online (Sandbox Code Playgroud)

我的Vite配置是:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

export default defineConfig({
  plugins: [react()],
}
Run Code Online (Sandbox Code Playgroud)

我的 Vitest 配置是:

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
  },
})
Run Code Online (Sandbox Code Playgroud)

这是运行 Vitest 时得到的。如果我直接运行 Jest

jest
Run Code Online (Sandbox Code Playgroud)

或者

node --experimental-vm-modules node_modules/jest/bin/jest.js 
Run Code Online (Sandbox Code Playgroud)

我得到:

 SyntaxError: /home/durrantm/Dropnot/vite/thedeiscorecard-vite/src/App.test.tsx: 
 Support for the experimental syntax 'jsx' isn't currently enabled
Run Code Online (Sandbox Code Playgroud)

Tac*_*hin 21

您的测试代码正在使用全局模式,您必须启用它:

vitest.config.ts

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
    globals: true
  },
})
Run Code Online (Sandbox Code Playgroud)

另外,如果您使用打字稿,您需要添加样式以受益于提示:tsconfig.json

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
    globals: true
  },
})
Run Code Online (Sandbox Code Playgroud)

尽管 vitest API 被设计为 jest 友好,但这并不意味着 jest 可以运行为 vitest 编写的测试代码


The*_*lie 5

您需要describe从 vitest 导入。

import { describe } from 'vitest';
Run Code Online (Sandbox Code Playgroud)