You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:27:33