Mock utility function that is being used on script load

Viewed 304

For simplicity I created a sample app in stackblitz.

The Hello component uses a utility function that I need to mock in order to test it.

const hmmm = mockMe();

const Hello = () => (
  <div>
    <h1>Hello StackBlitz!</h1>
    <p>{hmmm}</p>
  </div>
);

I tried several ways to mock the function, for example:

import * as utils from '../utils';

describe('Hello component', () => {
    it('should mock the utility function', () => {
        jest.spyOn(utils , 'mockMe').mockReturnValue("Mocked!");
        // render the component and test it
    }
}

My problem is that Hello.js runs before the test file. So, it executes the utility function before the mock is applied.

The only solution I could think of is to change the component code and move the call to the utility inside the render function. I would like to avoid this change.

Is there a way to mock the utility function and keep the code unchanged?

1 Answers

Before using the methods from the utils you need to mock the utils folder. For example, jest.mock('../utils');

Related