如何在React JS中使用Jest Mock函数?求助解决jest.mock不是函数错误
I've run into this exact issue before when working with Jest in Codesandbox—let's break down why this happens and how to fix it.
First, let's recap the error you're seeing:
TypeError: jest.mock is not a function at evaluate (https://oq7kwzrnj5.codesandbox.io/src/ListItem.spec.js:21:6) at r.a (https://codesandbox.io/static/js/sandbox.f3fc5e5b.js:5354:971) at e.value (https://codesandbox.io/static/js/sandbox.f3fc5e5b.js:5413:270) at e.value (https://codesandbox.io/static/js/sandbox.f3fc5e5b.js:5386:23195) at e.value (https://codesandbox.io/static...
Common Causes & Fixes
1. Missing Jest Global Injection
Codesandbox's default React/JS templates don't always inject the global jest object automatically, especially if you're running tests in a browser-like environment instead of a Node.js context.
Fix: Explicitly import Jest's globals at the top of your test file:
import { jest } from '@jest/globals';
Once imported, you can use jest.mock() as expected.
2. Wrong Codesandbox Template
If you started with a generic React template instead of a Jest-specific one, your environment might not be set up to support Jest's core functions.
Fix:
- Create a new Codesandbox using the "Jest" template (search for it in the template gallery)
- Migrate your test files and components to this new sandbox—this ensures all Jest globals and dependencies are pre-configured out of the box.
3. ES Module vs CommonJS Conflicts
If your project uses ES modules (via "type": "module" in package.json), the global jest variable might not be available unless you configure Jest to handle it.
Fix:
Add this Jest config to your package.json file:
{ "jest": { "globals": { "jest": true } } }
Alternatively, install and use the babel-plugin-jest-hoist plugin to ensure jest.mock() is hoisted correctly in ES module files.
4. Fallback: Manual Mocking
If none of the above work, you can skip jest.mock() entirely and use manual mocking with spies:
// Instead of jest.mock('./myModule') import myModule from './myModule'; jest.spyOn(myModule, 'targetFunction').mockReturnValue('mocked output');
内容的提问来源于stack exchange,提问作者user5711656

