参考错误:Jest环境被拆除后,“导入”文件

时间:2019-05-07 19:33:44

标签: react-native jestjs

我是测试React本机应用程序的新手。我从Jest开始,运行了名为App-test.js的测试,该测试通过了,但出现参考错误:Jest环境被破坏后,您正在尝试import一个文件。

我尝试过:

    jest.useFakeTimers();

    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"
      ]
   }

1 个答案:

答案 0 :(得分:1)

尝试在您的 setup.js 文件中添加测试此行的所有设置:

// 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);

这将确保在您运行测试后组件将被卸载