用jest和enzyme给react组件写测试,不知如何配置

最近准备给react组件库写测试,选了jest和enzyme,但是按照各大教程和官网没有一个配置成功的,来求助。
要测试的组件是用的react和typescript写的。

test文件

import React from 'react';
import { shallow } from 'enzyme';
describe('errorpage', () => {
  test('get errorpage', () => {
    // 这个<div></div>是我测试写的,本来是引入的一个组件
    const wrapper = shallow(<div></div>);
  });
});

运行测试时报的错:

yarn run v1.12.3
$ jest
 FAIL  __test__/errorpage.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

       const wrapper = enzyme_1.shallow(<div></div>);
                                             ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (../../node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (../../node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.129s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

相关配置

// babel.config.js
module.exports = {
  presets: [
      [
          "@babel/preset-env",
          {
              targets: {
                  node: "current"
              }
          }
      ]
  ],
  plugins: ["transform-es2015-modules-commonjs"]
};
// jest.config.js
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    "^.+\\.js$": "babel-jest",
    "^.+\\.(ts|tsx)$": "ts-jest"
  },
  // transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"],
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  collectCoverage: false,
  globals: {
    'ts-jest': {
      diagnostics: false
    }
  }
};
// tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "baseUrl": ".",
    "experimentalDecorators": true,
    "jsx": "preserve",
    "lib": [
      "es6",
      "es7",
      "dom"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "paths": {},
    "preserveConstEnums": true,
    "removeComments": false,
    "outDir": "./dist/", /* Redirect output structure to the directory. */
    "rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "sourceMap": false,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "target": "es2016",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node",
      "react",
      "react-dom"
    ]
  },
  "exclude": [
    "**/dist/*"
  ],
  "include": [
    "./src/**/*"
  ]
}

做过的尝试

在网上搜索了这个报错,只有下面这篇相关性较大,但是照着做了,也还是报错。
https://www.cnblogs.com/xueyo...
请各位大佬帮忙看看,或者一起研究组件的测试~

阅读 3.8k
2 个回答

已经解决了babel.config.js的preset没有配置正确。

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current"
        }
      }
    ],
    ["@babel/preset-typescript"],
    ["@babel/preset-react"]
  ]
};

之前只是配置了preset-env,babel不能解析react和typescript,所以加上了["@babel/preset-typescript"],["@babel/preset-react"]就好了。

你可能要把 ts 的 target 降一下,比如降到 es5。

推荐问题