测试完成后,反应本机+ ts-jest +酶挂起

时间:2020-01-14 16:34:23

标签: unit-testing react-native jestjs enzyme

我正在为React本机应用程序创建单元测试,结果是,在测试启动之后,它挂起了,而终端没有任何响应。我尝试使用--forceExit--detectOpenHandles记录任何问题。但是终端继续如下:

jest terminal run 我已经有了Intellij IDE,并在其上运行了相同的测试,我得到了这个结果

intellij test

请注意,在Running Tests...上写有加载图标的位置,即使在测试完成后,测试仍继续在Intellij上运行。

这是我的测试代码:

/**
 * @jest-environment jsdom
 */
import React from 'react';
import { mount, ReactWrapper, shallow } from 'enzyme';
import AnotherComponent from 'components/AnotherComponent';
// @ts-ignore
import { mocking } from './helpers/mockedTheme';
import TestComponent from 'components/TestComponent';

export const shallowWithTheme = (children: any) => (
  // @ts-ignore
  shallow(children, { mocking })
);

describe('Test Components', () => {
  describe('Test Component', ()=>{
    it('Test shallow with theme', () => {
      const element = shallowWithTheme(<TestComponent componentProp={"test"}/>);
      //@ts-ignore
      expect(element).toExist();
    });
  });
  describe('Test AnotherComponent', () =>{
    it('AnotherComponent with button', () => {
      const wrapper = shallowWithTheme(
        <AnotherComponent  icon="qr-code"
                         title='component title'
                         description='component description'
                         buttonText='go'
      />);
      // @ts-ignore
      expect(wrapper).toExist();
    });

    it('AnotherComponent without button', () => {
      const wrapper = shallow(
        <AnotherComponent  icon="qr-code"
                         title='component title'
                         description='component description'
        />);
      //@ts-ignore
      expect(wrapper).toExist();
    });
  });
});

组件AnotherComponentTestComponent与另一种样式嵌套。例如,

\\ TestComponent
import React from 'react';
import { MainContentView } from 'components/TestComponent/TestComponent.styles';
import { throwJSError } from 'reduxRoot/util/error';
import { withTheme } from 'styled-components/native';
import { Text } from 'react-native';

class TestComponent extends React.Component {
  render() {
    try {
      return (
            <MainContentView>
              <Text>Text</Text>
            </MainContentView>
      );
    } catch (err) {
      throwJSError(err, 'TestComponent/render');
      return null;
    }
  }
}

export default withTheme(TestComponent);

样式MainContentView是一个styled.component,例如: export const MainContentView = styled.View` flex: 1; backgroundColor: #FFFFFF;`;

这是我的笑话---调试

{
  "configs": [
    {
      "automock": false,
      "browser": false,
      "cache": true,
      "cacheDirectory": "/private/var/folders/rk/rnc3852s3y56rx7bypry2qz92b2nhd/T/jest_j25hjh",
      "clearMocks": false,
      "coveragePathIgnorePatterns": [
        "/node_modules/"
      ],
      "cwd": "<root-to-my-project>",
      "dependencyExtractor": null,
      "detectLeaks": false,
      "detectOpenHandles": true,
      "errorOnDeprecated": false,
      "filter": null,
      "forceCoverageMatch": [],
      "globalSetup": null,
      "globalTeardown": null,
      "globals": {
        "ts-jest": {
          "babelConfig": true,
          "isolatedModules": true
        }
      },
      "haste": {
        "defaultPlatform": "ios",
        "platforms": [
          "android",
          "ios",
          "native"
        ],
        "hasteImplModulePath": "<root-to-my-project>/node_modules/react-native/jest/hasteImpl.js",
        "providesModuleNodeModules": [
          "react-native"
        ]
      },
      "moduleDirectories": [
        "node_modules"
      ],
      "moduleFileExtensions": [
        "js",
        "json",
        "jsx",
        "ts",
        "tsx",
        "node"
      ],
      "moduleNameMapper": [
        [
          "reduxRoot(.*)$",
          "<root-to-my-project>/redux$1"
        ],
        [
          "screens(.*)$",
          "<root-to-my-project>/src/screens$1"
        ],
        [
          "^React$",
          "<root-to-my-project>/node_modules/react/index.js"
        ]
      ],
      "modulePathIgnorePatterns": [
        "<root-to-my-project>/node_modules/react-native/Libraries/react-native/"
      ],
      "name": "a1c9dcb3024a2c47c9517df7e59341e3",
      "prettierPath": "prettier",
      "resetMocks": false,
      "resetModules": false,
      "resolver": null,
      "restoreMocks": false,
      "rootDir": "<root-to-my-project>",
      "roots": [
        "<root-to-my-project>"
      ],
      "runner": "jest-runner",
      "setupFiles": [
        "<root-to-my-project>/node_modules/react-native/jest/setup.js",
        "<root-to-my-project>/native/node_modules/react-native-gesture-handler/jestSetup.js"
      ],
      "setupFilesAfterEnv": [
        "<root-to-my-project>/jest.setup.js"
      ],
      "skipFilter": false,
      "snapshotSerializers": [],
      "testEnvironment": "<root-to-my-project>/node_modules/jest-environment-node/build/index.js",
      "testEnvironmentOptions": {},
      "testLocationInResults": false,
      "testMatch": [
        "**/__tests__/*.(ts|tsx|js)"
      ],
      "testPathIgnorePatterns": [
        "/node_modules/"
      ],
      "testRegex": [],
      "testRunner": "<root-to-my-project>/node_modules/jest-jasmine2/build/index.js",
      "testURL": "http://localhost",
      "timers": "real",
      "transform": [
        [
          "^.+\\.tsx?$",
          "<root-to-my-project>/node_modules/ts-jest/dist/index.js"
        ],
        [
          "\\.js$",
          "<root-to-my-project>/node_modules/react-native/jest/preprocessor.js"
        ],
        [
          "^.+\\.(js|ts|tsx)$",
          "<root-to-my-project>/node_modules/babel-jest/build/index.js"
        ],
        [
          "^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$",
          "<root-to-my-project>/node_modules/react-native/jest/assetFileTransformer.js"
        ]
      ],
      "transformIgnorePatterns": [
        "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community)"
      ],
      "watchPathIgnorePatterns": []
    }
  ],
  "globalConfig": {
    "bail": 0,
    "changedFilesWithAncestor": false,
    "collectCoverage": false,
    "collectCoverageFrom": null,
    "coverageDirectory": "<root-to-my-project>/coverage",
    "coverageReporters": [
      "json",
      "text",
      "lcov",
      "clover"
    ],
    "coverageThreshold": null,
    "detectLeaks": false,
    "detectOpenHandles": true,
    "errorOnDeprecated": false,
    "expand": false,
    "filter": null,
    "globalSetup": null,
    "globalTeardown": null,
    "json": false,
    "listTests": false,
    "maxConcurrency": 5,
    "maxWorkers": 3,
    "noStackTrace": false,
    "nonFlagArgs": [],
    "notify": false,
    "notifyMode": "failure-change",
    "passWithNoTests": false,
    "projects": null,
    "rootDir": "<root-to-my-project>",
    "runTestsByPath": false,
    "skipFilter": false,
    "testFailureExitCode": 1,
    "testPathPattern": "",
    "testResultsProcessor": null,
    "testSequencer": "<root-to-my-project>/node_modules/@jest/test-sequencer/build/index.js",
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": true,
    "watch": false,
    "watchman": true
  },
  "version": "24.9.0"
}

最后但并非最不重要的一点是,我的jest.setup.js模拟了运行环境所需的全部内容:

import { NativeModules } from 'react-native';
import 'jest-styled-components';
import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { configure } from 'enzyme';

/**
 * Set up Enzyme to mount to DOM, simulate events,
 * and inspect the DOM in tests.
 */
configure({ adapter: new Adapter() });


/**
 * Set up DOM in node.js environment for Enzyme to mount to
 */
const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
  Object.defineProperties(target, {
    ...Object.getOwnPropertyDescriptors(src),
    ...Object.getOwnPropertyDescriptors(target),
  });
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

jest.mock('react-navigation/src/routers/KeyGenerator', () => ({
  generateKey: jest.fn(() => 123),
}));

jest.mock('./node_modules/react-native-reanimated/src/ReanimatedEventEmitter');
jest.mock('./node_modules/react-native-reanimated/src/ReanimatedModule');

jest.mock('react-native-gesture-handler', () =>({
  State: jest.fn(),
  TapGestureHandler: jest.fn()
}));

NativeModules.RNCNetInfo = {
  getCurrentState: jest.fn(() => Promise.resolve()),
  addListener: jest.fn(),
  removeListeners: jest.fn()
};

jest.mock('react-native-device-info', () => {
  return {
    getVersion: jest.fn(() => Promise.resolve('1.0')),
    getApplicationName: jest.fn(() => Promise.resolve('My App')),
    getModel: jest.fn(() => Promise.resolve('iPhone 11')),
    hasNotch: jest.fn(),
  };
});

jest.mock('services/theme/scaling', () => ({
    scale: jest.fn()
  })
);

jest.mock('services/theme/styles', () => ({
    themeVal: jest.fn()
  })
);


NativeModules.StatusBarManager = {
  HEIGHT : 20,
  getHeight: jest.fn()
};

NativeModules.ParentBridge ={
  partnerId: jest.fn()
};

NativeModules.CTNConfig =  { buildEnvironment: 'Development'};

所以。有人知道如何正确配置我的代码,以便能够看到我的单元测试完成并且不再挂起吗?

ps .:我注意到我收到了一条警告消息,不知道这与测试挂起的原因有关:

    Warning: Async Storage has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-community/async-storage' instead of 'react-native'. See https://github.com/react-native-community/react-native-async-storage```

0 个答案:

没有答案