'React & Jest: How to isolate 3rd-party module mock?

I have a component which uses ouibounce to detect an event and render a modal. But this component also listens for other events to render different modals.

I'm trying to write a unit test for each listener. In one test, I need to mock ouibounce so that it immediately executes the callback it is given, which will render the appropriate modal. However, it is crucial that this mock does not exist in other tests.

At first I had the mock at the top of the test file, outside the suite, which is the only place it will work.

imports ...

jest.mock('ouibounce', () => {
    return (unused, opts) => opts.callback()
});

describe(...)

I couldn't figure out a way to change or remove the mock at the end of a specific test though.

I saw discussions of doMock such as the answer to this question: Jest: restore original module implementation on a manual mock

doMock looks like the right approach, but I can't figure out how to get that to work with a React component. It looks like I need to do the following steps in order:

  1. mock ouibounce locally
  2. import ouibounce
  3. import the component being tested

However, I'm stuck on step 3. in either case, import('./Component').then(c => ...) or c = require('./Component') I am getting an object that won't mount. Okay, that object has a "default" function, so I will try to mount c.default(). But that is the wrong approach, because now React is complaining that "Hooks can only be called inside of the body of a function component" (which they definitely are). So I think I have run out of threads here and I am missing something.

and fyi I am using ReactDOM.render() to mount the component.

How can I mock ouibounce for just one test?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source