Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference error: `import` a file after the Jest environment has been torn down

I am new to testing react native apps. I started with Jest and I run the test called App-test.js which passes, but I get the reference error: You are trying to import a file after the Jest environment has been torn down.

I have tried:

    jest.useFakeTimers();

and

    jest.useFakeTimers();
    Date.now = jest.fn(() => 1503187200000);

jestSetupFile.js

    import mockAsyncStorage from '@react-native-community/async- 
    storage/jest/async-storage-mock';

    import { NativeModules } from 'react-native';

    jest.mock('@react-native-community/async-storage', () => 
    mockAsyncStorage);
    jest.useFakeTimers();
    Date.now = jest.fn(() => 1503187200000);

    Object.assign(NativeModules, {
      RNGestureHandlerModule: {
        attachGestureHandler: jest.fn(),
        createGestureHandler: jest.fn(),
        dropGestureHandler: jest.fn(),
        updateGestureHandler: jest.fn(),
        State: {},
        Directions: {},
      },
     PlatformConstants: {
        forceTouchAvailable: false,
     },
   });

package.json

    "jest": {
        "preset": "react-native",
        "transformIgnorePatterns": [
            "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|react-navigation-header-buttons|react-navigation-stack|@react-navigation)"
        ],
      "setupFiles": [
          "./jestSetupFile.js"
      ]
   }
like image 837
Laura Duran Velazquez Avatar asked May 07 '19 19:05

Laura Duran Velazquez


1 Answers

try to add in your setup.js file where you have everything setup for testing this line:

// this should be at the top of the file 
import { cleanup } from '@testing-library/react-native';`

// and also this line (probably) at the end of the file or just bellow all imports:
afterEach(cleanup);

which will make sure after you run the test the component will be unmounted

like image 171
Stefan Morcodeanu Avatar answered Sep 23 '22 12:09

Stefan Morcodeanu