Skip to content

TypeError: jest.fn is not a function

Error message

                jest.fn is not a function
              

Quick summary

The test tries to use jest.fn() but Jest is not available in the current environment. This happens when the test runner isn't Jest or Jest isn't configured.

Why this happens

  • The test file is being run by a different test runner (Mocha, Vitest) that doesn't have jest global.

  • Jest is not installed or not in the project dependencies.

  • The Jest configuration doesn't set up the test environment correctly.

  • The test file has a typo or incorrect import.

Minimal example

✗ Broken code
// Running with Vitest but using Jest API
const mock = jest.fn(); // jest is not defined
✓ Fixed code
// Using Vitest API
import { vi } from 'vitest';
const mock = vi.fn();

Vitest uses vi instead of jest. Import vi from vitest and use vi.fn().

How to diagnose

  • Check package.json to verify Jest is installed: look for 'jest' in devDependencies.

  • Check the test script in package.json — it should run 'jest' or 'jest --config'.

  • Verify the test file extension matches Jest's test file pattern (e.g., *.test.js).

  • Check if you're using Vitest — it uses 'vi.fn()' instead of 'jest.fn()'.

How to fix

  • Install Jest: npm install --save-dev jest

  • If using Vitest, replace jest.fn() with vi.fn() and import { vi } from 'vitest'.

  • Ensure the test script in package.json is correct: "test": "jest".

How to prevent

  • Verify your test runner is correctly configured before writing tests.

  • If migrating from Jest to Vitest, update all jest.* references to vi.*.

Related Resources

Related Glossary

Related Lessons

← Back to language