Mocking private helper functions with Jest?

For example if you have the module:

const sum = (a, b) => {
  return a + b;

const sumWrapper = (a, b) => {
  return sum(a, b);
export default sumWrapper;

and you’re trying to test the sumWrapper function. However, you’d like to mock the sum function to

const sum = jest.fn((a, b) => a * b);

However, because this implementation was not given to sumWrapper when it was defined sum still does the original addition function.
What would be the best way to mock this implementation and give sumWrapper access to the new multiplication sum mock function?

This is useful to me because I have a function getAddress() that gets the address of a smart contract depending on the current network. I’d like to mock the getNetwork function provided by web3 to return a network of my choosing to better test the code.

Source: JavaSript – Stack Overflow

November 25, 2021
Category : News
Tags: javascript | jestjs | mocking

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.