Vitest中使用jest.mock报错:ReferenceError: jest is not defined
解决方案:继续使用
jest.mock的配置方法 可以继续沿用jest.mock的写法,只需完成两处配置调整即可解决jest is not defined的错误:
1. 配置Vitest全局变量映射
修改vitest.config.ts,将全局jest对象映射到Vitest的vi对象,让jest.mock自动对应vi.mock:
/// <reference types="vitest" /> import react from '@vitejs/plugin-react'; import tsconfigPaths from 'vite-tsconfig-paths'; import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [react(), tsconfigPaths()], test: { // 将原globals: true改为对象形式,添加jest到vi的映射 globals: { jest: 'vi' }, environment: 'jsdom', include: ['**/*.test.tsx'], setupFiles: 'setupTests.ts', }, });
2. 修复TypeScript类型报错
为让TypeScript识别全局jest变量,调整tsconfig.json的类型配置:
在compilerOptions.types数组中添加'vitest/globals':
{ "compilerOptions": { // 保留原有配置... "types": ["vitest/globals"] }, // 保留原有include/exclude配置... }
若不想修改全局tsconfig,也可在单个测试文件顶部添加类型引用:
/// <reference types="vitest/globals" />
验证效果
配置完成后,你可以继续使用jest.mock、jest.spyOn等熟悉的API,Vitest会自动处理为对应的vi方法,完全兼容日常mock场景。少数Jest边缘API可能存在差异,但绝大多数通用用法无需调整。
内容的提问来源于stack exchange,提问作者medev21
相关产品推荐
相关产品推荐

