DEV Community

Lem Dulfo
Lem Dulfo

Posted on

Fixing "Trying to import a file after Jest has been torn down"

This is the story of how I solved ReferenceError: You are trying to import a file after the Jest environment has been torn down.

Previously, I wrote about how I pushed an anti-pattern to our main branch. I got a comment that it was just a quick fix and didn't solve the actual bug. Fair enough!

Before we get to the solution, I want to provide some context. We had a react-native-modal that had the following behavior:
onClick -> showLoadingIndicator -> doSomething -> send analytics -> hideLoadingIndicator -> close modal

The previous test looked like:

fireEvent.press(modalButton);
await waitForElementToBeRemoved(() => loadingIndicator);
expect(analytics).toHaveBeenCalled();
Enter fullscreen mode Exit fullscreen mode

The tests were passing, but was throwing an error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

  at Object.get InteractionManager [as InteractionManager] (node_modules/react-native/index.js:158:12)
  at node_modules/react-native-modal/dist/modal.js:332:26
  at tryCallOne (node_modules/promise/lib/core.js:37:12)
  at node_modules/promise/lib/core.js:123:15
  at flush (node_modules/asap/raw.js:50:29)
Enter fullscreen mode Exit fullscreen mode

Going to react-native/index.js line 158 told me I was importing Modal:

  get Modal(): Modal {
    return require('./Libraries/Modal/Modal');
  },
Enter fullscreen mode Exit fullscreen mode

Following the stacktrace up, and going to modal.js line 332 yielded:

this.close();
Enter fullscreen mode Exit fullscreen mode

Going to raw.js and looking at the flush code, it's documented as "The flush function processes all tasks that have been scheduled".

When we put that all together, what was effectively happening was my test was over and successful, Jest was torn down, but the call to close() had been queued previously and getting ran by flush. Since close() was a Modal reference, the error told me I was importing Modal after Jest has been torn down. It all makes sense, but to be honest it was a puzzle that needed to be pieced together.

The non-antipattern solution:

fireEvent.press(modalButton);

await waitFor(() => 
  expect(modal.props).toHaveProperty("visible", false)
);

expect(analytics).toHaveBeenCalled();
Enter fullscreen mode Exit fullscreen mode

So what did we learn here? Two things. First: If you have the time, dig deeper into the stack trace to really understand a crappy error message. Second: Be wrong on the internet. Be hacky. Someone will call you out, and you might learn a thing or two.

Top comments (0)