How To Spy On An Exported Function In Jest
September 03, 2021 - 1 minutes
The spyOn
function is one of the most powerful utility functions in Jest.
It allows you to spy on a function, observe interactions, and mock them accordingly.
But to spy on a named import in Jest isn’t straightforward due to the arguments that the function accepts.
Take a look at the following example where I’m importing a function functionToMock
from the module @module/api
:
import { functionToMock } from '@module/api';
jest.spyOn(???, 'functionToMock').mockReturnValue({ someObjectProperty: 42 });
I want to spy on the named export, but what should I provide to the jest.spyOn
function as the first argument?
The API requires an entire module or object as its first argument and the particular property that should be spied on as its second argument.
But in this case, we’re trying to spy on an imported function so we don’t have such an object available.
Luckily, there is a simple way to solve this.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest.spyOn
function. That would look like this:
import * as moduleApi from '@module/api';
// Somewhere in your test case or test suite
jest.spyOn(moduleApi, 'functionToMock').mockReturnValue({ someObjectProperty: 42 });
One caveat to this approach is that there’s the chance that you will run across a TypeError: Cannot redefine property: functionToMock at Function.defineProperty (<anonymous>)
. In that case, you can’t use the spyOn
function to mock the exported function. To fix this error, you’ll need a different method to mock it.