Skip to content

TypeError: jest.fn 是不 函数

错误信息

                jest.fn 是不 函数
              

快速摘要

测试 tries 到 use jest.fn() 但 Jest 是不 available in current 环境. 这个 happens 当测试 runner isn't Jest or Jest isn't 配置.

为什么发生

  • 测试 file 是是 运行通过不同测试 runner (Mocha, Vitest) 那个 doesn't 有 jest 全局.

  • Jest 是不 安装 or 不 in 项目 dependencies.

  • Jest 配置 doesn't 设置测试环境正确地.

  • 测试 file 有 typo or 不正确导入.

最小示例

✗ 错误代码
// Running with Vitest but using Jest API
const mock = jest.fn(); // jest is not defined
✓ 修复代码
// Using Vitest API
import { vi } from 'vitest';
const mock = vi.fn();

Vitest uses vi 相反的 jest. 导入 vi 从 vitest and use vi.fn().

如何诊断

  • 检查包.JSON 到验证 Jest 是安装: look for 'jest' in devDependencies.

  • 检查测试 script in 包.JSON — 它应该运行 'jest' or 'jest --配置'.

  • 验证测试 file extension matches Jest's 测试 file 模式 (e.g., *.测试.js).

  • 检查如果你're using Vitest — 它 uses 'vi.fn()' 相反的 'jest.fn()'.

如何修复

  • 安装 Jest: npm 安装 --保存-dev jest

  • 如果 using Vitest, replace jest.fn() 使用 vi.fn() and 导入 { vi } 从 'vitest'.

  • Ensure 测试 script in 包.JSON 是正确: "test": "jest".

如何预防

  • 验证你的测试 runner 是正确地配置之前编写测试.

  • 如果 migrating 从 Jest 到 Vitest, 更新所有 jest.* 引用到 vi.*.

相关资源

相关术语

相关课程

← 返回语言