πŸ’‘ 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 β€’ Read time 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.

Copied to clipboard!
import * as utils from 'utils'

utils.sum = jest.fn()
Mock the sum function from the utils module

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:

Copied to clipboard! Playground
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)

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.

Copied to clipboard!
import * as utils from 'utils'

utils.sum = jest.fn().mockReturnValue(2)
mockReturnValue accepts and arbitrary value that will be returned
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.