Mock only one function from module but leave rest with original functionality

The highlight of this answer is jest.requireActual(), this is a very useful utility that says to jest that “Hey keep every original functionalities intact and import them”.

jest.mock('./utilities.js', () => ({
  ...jest.requireActual('./utilities.js'),
  speak: jest.fn(),
}));

Let’s take another common scenario, you’re using enzyme ShallowWrapper and it doesn’t goes well with useContext() hook, so what’re you gonna do? While i’m sure there are multiple ways, but this is the one I like:

import React from "react";

jest.mock("react", () => ({
  ...jest.requireActual("react"), // import and retain the original functionalities
  useContext: jest.fn().mockReturnValue({foo: 'bar'}) // overwrite useContext
}))

The perk of doing it this way is that you can still use
import React, { useContext } from "react" in your original code without worrying about converting them into React.useContext() as you would if you’re using jest.spyOn(React, ‘useContext’)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)