jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.1k stars 6.44k forks source link

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

Closed ronnaf closed 6 years ago

ronnaf commented 6 years ago

🐛 Bug Report

I have a component that makes use of Animated component from react native. I started writing a test case to simulate onPress of a component, which calls a function that has Animated.timing in it, and setState.

jest works fine, but the tests never stops running, and one unrelated test case that I've written before never seem to pass now (which passed before).

running jest --watch, I get this error:

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

      at Function.bezier (node_modules/react-native/Libraries/Animated/src/Easing.js:113:21)
      at ease (node_modules/react-native/Libraries/Animated/src/Easing.js:34:24)
      at TimingAnimation._easing (node_modules/react-native/Libraries/Animated/src/Easing.js:133:18)
      at TimingAnimation.onUpdate (node_modules/react-native/Libraries/Animated/src/animations/TimingAnimation.js:107:45)

 RUNS  src/__tests__/SlideDownMenu.test.js

/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:114
      return _bezier(x1, y1, x2, y2);
             ^
TypeError: _bezier is not a function
    at Function.bezier (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:224:12)
    at ease (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:94:21)
    at TimingAnimation._easing (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/Easing.js:255:16)
    at TimingAnimation.onUpdate (/home/nrion/Desktop/mobile-ui/PriceInsight_app/node_modules/react-native/Libraries/Animated/src/animations/TimingAnimation.js:138:14)
    at ontimeout (timers.js:386:11)
    at tryOnTimeout (timers.js:250:5)
    at Timer.listOnTimeout (timers.js:214:5)

Expected behavior

Tests passes

Link to repl or repo (highly encouraged)

repl.it demo: https://repl.it/repls/PartialGrimyMetadata

Run npx envinfo --preset jest

Environment:
  OS: Linux 4.14
  Node: 6.14.2
  Yarn: 1.7.0
  npm: 3.10.10
  Watchman: Not Found
  Xcode: N/A
  Android Studio: Not Found
ronnaf commented 6 years ago

Found https://github.com/facebook/jest/issues/4359

Closing this issue

chris-ryu commented 5 years ago

I have same problem.

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

  at Object.get BackHandler [as BackHandler] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:227:12)
  at new NavigationContainer (node_modules/@react-navigation/native/dist/createAppContainer.js:190:35)
  at constructClassInstance (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3459:18)
  at updateClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6785:5)
  at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7742:16)
  at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11413:12)

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

  at Object.<anonymous>.module.exports (node_modules/react-native/jest/mockComponent.js:20:31)
  at Object.user:/Users/test/Projects/WellFamily/rnapp/node_modules/react-native/Libraries/Modal/Modal.js: (node_modules/react-native/jest/setup.js:11:10)
  at Object.get Modal [as Modal] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:71:12)
  at ActionSheetContainer.render (node_modules/native-base/dist/src/basic/Actionsheet.js:169:57)

● Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "The above error occurred in the component: in NavigationContainer (created by _default) in View (created by Component) in Component (at Root.js:13) in Root (created by Styled(Root)) in Styled(Root) (created by _default) in _default (created by Setup) in PersistGate (created by Setup) in Provider (created by Setup) in StyleProvider (created by Setup) in Setup (created by App) in App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.".

  at CustomConsole.error (node_modules/@jest/console/build/CustomConsole.js:123:10)
  at logCapturedError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9215:13)
  at logError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9251:5)
  at update.callback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10161:5)
  at callCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8531:12)
  at commitUpdateEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8570:7)
  at commitUpdateQueue (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8561:3)
  at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9481:11)
  at commitAllLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10829:7)
  at Object.invokeGuardedCallbackImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2302:10)

package.json { "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "eject": "expo eject", "test": "node_modules/.bin/jest", "test:debug": "node --inspect-brk node_modules/jest/bin/jest.js --runInBand" }, "dependencies": { "@builderx/icons": "^0.1.7", "@builderx/utils": "^0.1.6", "@expo/vector-icons": "^9.0.0", "@expo/videoplayer": "^0.4.0", "dot-prop-immutable": "^1.5.0", "expo": "^32.0.6", "lodash": "^4.17.11", "moment": "^2.24.0", "native-base": "^2.12.1", "query-string": "^6.2.0", "react": "16.5.0", "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz", "react-native-axios": "^0.17.1", "react-native-easy-grid": "^0.2.1", "react-native-elements": "^1.1.0", "react-native-htmlview": "^0.13.0", "react-native-modalbox": "^1.7.1", "react-native-progress": "^3.6.0", "react-native-stopwatch-timer": "0.0.20", "react-navigation": "^3.0.9", "react-redux": "^6.0.0", "redux": "^4.0.1", "redux-form": "^8.1.0", "redux-persist": "^5.10.0", "redux-saga": "^1.0.1", "redux-thunk": "^2.3.0", "reduxsauce": "^1.0.1" }, "devDependencies": { "babel-preset-expo": "^5.0.0", "jest": "^24.5.0", "jest-expo": "^32.0.0", "react-test-renderer": "^16.8.6", "remote-redux-devtools": "^0.5.16" }, "jest": { "preset": "jest-expo", "transformIgnorePatterns": [ "node_modules/(?!((jest-)?react-native|react-clone-referenced-element|expo(nent)?|@expo(nent)?/.|react-navigation|@react-navigation/.|sentry-expo|native-base|@builderx))" ] }, "private": true }

tarunjuneja commented 5 years ago

I am on react-native 0.60 was struggling with same error

I solved it by adding jest.useFakeTimers();

With above it's extremely important to understand this

jest.useFakeTimers() mocks out setTimeout and other timer functions with mock functions.

If running multiple tests inside of one file or describe block, jest.useFakeTimers(); can be called before each test manually or with a setup function such as beforeEach.

Not doing so will result in the internal usage counter not being reset.

parnekov commented 5 years ago

I am on react-native 0.60 was struggling with same error

I solved it by adding jest.useFakeTimers();

With above it's extremely important to understand this

jest.useFakeTimers() mocks out setTimeout and other timer functions with mock functions.

If running multiple tests inside of one file or describe block, jest.useFakeTimers(); can be called before each test manually or with a setup function such as beforeEach.

Not doing so will result in the internal usage counter not being reset.

Works for me! thanks!

daveols commented 4 years ago

Mocking the timers caused cascading errors in my tests.

I'm using testing-library and was able to fix this issue by adding afterEach(cleanup) before my render helper function definition.

f4z3k4s commented 4 years ago

I am using react-native-testing-library and what resolved this error for me was to simply make the callback of the test case async like

it('your test case', () => {...})

becomes:

it('your test case', async () => {...})
jwoodmansey commented 4 years ago

I am using react-native-testing-library and what resolved this error for me was to simply make the callback of the test case async like

it('your test case', () => {...})

becomes:

it('your test case', async () => {...})

Thanks, this pointed me in the right direction!

I'd got this error with a dangling Promise in my test. Had an async function but missed an await.

victorwads commented 4 years ago

I am using react-native-testing-library and what resolved this error for me was to simply make the callback of the test case async like

it('your test case', () => {...})

becomes:

it('your test case', async () => {...})

Thanks, this pointed me in the right direction!

I'd got this error with a dangling Promise in my test. Had an async function but missed an await.

This works for me

abbasmoosavi commented 4 years ago

I am using react-native-testing-library and what resolved this error for me was to simply make the callback of the test case async like

it('your test case', () => {...})

becomes:

it('your test case', async () => {...})

Safe my time, Thank so much my bro

lukewlms commented 4 years ago

I was getting this issue while testing Apollo with react-native-testing-library.

In this case there were two queries, in a parent and child component. The parent query needed to resolve before the child rendered and fired its query.

The solution was to run the wait() function twice rather than just once. I assume the double-fire is necessary to ensure both queries run. The error message is very opaque though.

test("...", () => {
  const rr = render(...);
  await wait();
  await wait(); // Child query must also run
  expect(...);
}

// Wait a tick so the query runs
// https://www.apollographql.com/docs/react/development-testing/testing/#testing-final-state
export async function wait(ms = 0) {
  await act(async () => {
    return new Promise(resolve => {
      setTimeout(resolve, ms);
    });
  });
}
youngjuning commented 3 years ago

image

write this into jest.setup.js:

import 'react-native/Libraries/Animated/src/bezier'; // for https://github.com/facebook/jest/issues/4710

@ronnaf

JosManMx commented 3 years ago

I was presenting this issue in a RN project.

I fixed changing "default props" in the tested component cause expected a function prop, but received an object, after add a empty function as default (() => null), solved the test problem.

my-name-is-nheo commented 3 years ago

deleting node_modules and NPM I solved it for me. hope it helps someone

samir-kutty commented 3 years ago

I believe sometimes this happens when your mocked component has async behaviour (state updates) in it, which takes a while to complete, but your test does not wait for it and ends prematurely leading to an "Async warning" or the above error "You are trying to import a file".

Now this might be a hack, but I found that the best way to solve this is to wait for a component to finish all its async behavior before we can start with the next steps. Calling an empty async callback usually does the trick. Here's an example:

it('renders component and waits for all async behavior to finish ', async () => {
    renderMockComponent(mockData);
    await act(async () => {}); //this is where the magic happens
    const allHiddenElementsAfterRendering = getAllByTestId('hiddenElements'); 
    expect(allHiddenElementsAfterRendering).toHaveLength(x);
  });

Hope this helps someone!

nabilfreeman commented 3 years ago

We have thousands of tests and this has been bugging me for a while. The stack trace is really unhelpful in finding the offending test so it's too easy for a dev to accidentally forget to await something and their test returns a false positive.

Made this patch to improve visibility of the problem.

patches/jest-runtime+25.5.4.patch

diff --git a/node_modules/jest-runtime/build/index.js b/node_modules/jest-runtime/build/index.js
index 35d64c0..2a82fcc 100644
--- a/node_modules/jest-runtime/build/index.js
+++ b/node_modules/jest-runtime/build/index.js
@@ -1190,7 +1190,43 @@ class Runtime {

     if (compiledFunction === null) {
       this._logFormattedReferenceError(
-        'You are trying to `import` a file after the Jest environment has been torn down.'
+`🚨
+🚨 🚨
+🚨 🚨 🚨
+🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+____          _____    _______ ______  _____ _______ _ 
+|  _ \\   /\\   |  __ \\  |__   __|  ____|/ ____|__   __| |
+| |_) | /  \\  | |  | |    | |  | |__  | (___    | |  | |
+|  _ < / /\\ \\ | |  | |    | |  |  __|  \\___ \\   | |  | |
+| |_) / ____ \\| |__| |    | |  | |____ ____) |  | |  |_|
+|____/_/    \\_\\_____/     |_|  |______|_____/   |_|  (_)
+                                                       
+Got this error from Jest: You are trying to \`import\` a file after the Jest environment has been torn down.
+
+This means you have a leaky promise somewhere and your test is not working properly.
+
+Find the offending test and make sure it is async, and await any function calls inside.
+
+The stack trace here is useless (thanks Jest), but it is probably the test suite right above or below this error.
+
+Don't ignore this.
+
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨 🚨
+🚨 🚨 🚨 🚨
+🚨 🚨 🚨
+🚨 🚨
+🚨`,
       );

       process.exitCode = 1;
thanksyouall commented 3 years ago

Try it:

it('your test case', (done) => {
  ...
  done() // <- calling at the end of the test.
})

It's cleaner that: it('your test case', async () => {...})

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.