Technical Blog

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.

After graduation, my career is entirely centered around learning and improving as a developer. I’ve began working full time as a React developer and I’ll be blogging about everything that I encounter and learn during this journey. This will range from improving communicational skills in a technical environment, becoming a better developer, improving technical skills in React and JavaScript, and discussing career related topics. In all of my posts, the focus will be on my personal experiences, learnings, difficulties, solutions (if present), and also flaws.

Written by Chak Shun Yu, a React frontend developer, former Storybook maintainer, and technical writer about React, testing, and career. You can find me on Twitter or check out my other articles.