开玩笑:具有反应导航的意外令牌导出

时间:2020-03-04 10:47:53

标签: react-native jestjs react-navigation

花了两天的时间研究之后,我终于耗尽了想法。

问题是使用withNavigation中的React-Navigation的组件。

当我运行Jest时,它抱怨指向withNavigation的令牌意外导出(React-Navigation)。

enter image description here

由于其他第三方库(例如Native Base)存在相同的问题,因此我得出结论transformIgnorePatterns必须存在一个问题。例如,我尝试了这个solution之间的相似之处,其中有许多相似之处。我也尝试调整babel.config,如GitHub上另一篇文章所建议。没用!也许有人有主意?请不要我使用TypeScript

如果我的Jestpackage.json部分,

  ...
  "jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
      "\\.(ts|tsx)$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "tsConfig": "tsconfig.jest.json"
      }
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|native-base|react-navigation|react-native-fabric)"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$"
  }

jest.config.js:

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

tsconfig.jest.json:

{
  "extends": "./tsconfig",
  "compilerOptions": {
    "jsx": "react",
    "module": "commonjs"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "noImplicitAny": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

babel.config.js:

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-typescript',
  ],
};

组件(测试):

imports ...

type Props = {}

const Test: React.FC<Props> = ({}) => {
  return (
    <View testID="test" style={styles.container}>
      <View>
        <Text testID="home">Home</Text>
        <ButtonNavigate title="Home" navigateTo="About" />
      </View>
    </View>
  );
};

export default withNavigation(Test);

测试:

import React from 'react';
import {render, fireEvent} from 'react-native-testing-library';

import Test from '../Test';

// NativeAnimatedHelper is not mocked by default on react native's jest setup file.
jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
//jest.mock('react-navigation', () => ({withNavigation: component => component}));

describe('Test', () => {
  test('rendering a component that uses withNavigation', () => {
    const {getByTestId} = render(
      <Test navigation={navigation}></Test>,
    );
    expect(getByTestId('test').toBeDefined());
  });
});

如果有人可以帮助,请先感谢。

1 个答案:

答案 0 :(得分:3)

这对我有用:

jest.mock('react-navigation', () => ({
  withNavigation: (Component) => (props) => (
    <Component navigation={{ navigate: jest.fn() }} {...props} />
  ),
}))

告诉我,如果它也对您有用。