πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
3 Ways to Mock Named Exports in Jest

3 Ways to Mock Named Exports in Jest

Using jest.fn, mockImplementation and mockReturnValue
Ferenc Almasi β€’ 2022 June 29 β€’ πŸ“– 1 min read
  • twitter
  • facebook

In order to mock named exports in Jest, you need to import all named exports from a file with an * and assign jest.fn to the method that needs to be mocked.

import * as utils from 'utils'

utils.sum = jest.fn()
Mock the sum function from the utils module
Copied to clipboard!

We can use an alias for the import so that we can access all named exports within an object. Now we can simply reassign one of the methods of utils to a mock function using jest.fn. We can also mock the implementation using mockImplementation:

import * as utils from 'utils'

const original = utils.sum

utils.sum = jest.fn().mockImplementation(() => {
    // Mock implementation goes here
})

// Restore mock
utils.sum = jest.fn().mockImplementation(original)
Copied to clipboard!

mockImplementation expects a callback function to be passed that describes the implementation. In case you need to restore the mock later on, we can save the original function into a variable, and call mockImplementation again with the original function.

You may also simply want to mock only the return value instead of the whole implementation. In order to mock a return value in Jest, we can use mockReturnValue.

import * as utils from 'utils'

utils.sum = jest.fn().mockReturnValue(2)
mockReturnValue accepts and arbitrary value that will be returned
Copied to clipboard!
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Courses

Recommended