React17 组件库自动化测试工具 Jest 配置报错及处理

1,838 阅读3分钟

Jest是一个令人愉快的 JavaScript 测试框架,专注于简洁明快。但是按照官网的配置,实际运行的时候,一个接一个的报错... 我花了半天踩坑,顺利跑通测试 demo...

配置

部分 package.json 配置

{
  "scripts": {
    "start": "dumi dev",
     //...
    "test": "jest",
    "test:coverage": "jest --coverage"
  },
  ...
  "devDependencies": {
    "@babel/core": "^7.14.3",
    "@babel/preset-env": "^7.14.4",
    "@babel/preset-react": "^7.13.13",
    "@babel/preset-typescript": "^7.13.0",
    "@types/enzyme": "^3.10.8",
    "@types/jest": "^26.0.23",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@umijs/test": "^3.0.5",
    "@wojtekmaj/enzyme-adapter-react-17": "^0.6.1",
    "babel-jest": "^27.0.2",
    "dumi": "^1.1.14",
    "enzyme": "^3.11.0",
    "father-build": "^1.19.1",
    "gh-pages": "^3.1.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.0.4",
    "jsdom": "^16.6.0",
    "lerna": "^3.22.1",
    "lint-staged": "^10.5.3",
    "prettier": "^2.2.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-test-renderer": "^17.0.2",
    "ts-jest": "^27.0.3",
    "typescript": "^4.1.3",
    "yorkie": "^2.0.0"
  }
}

jest --init 初始化配置

// jest.config.js
module.exports = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: "coverage",
    coverageProvider: "v8",
    testEnvironment: "jsdom",
}

babel.config.js 配置

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

测试 demo 如下

import React from 'react';
import { mount } from 'enzyme';
import { Empty } from '../src';

describe('describe', () => {
  it('test', () => {
    const wrapper = mount(<Empty/>);
    console.log(wrapper, 'wrapper');
  });
  expect(() => {}).not.toThrow();
});

报错

报错一

执行 npm run test 报错,重点看 Details,

 Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){@empty-prefix-cls: tiny-empty;
                                                                                      ^
    SyntaxError: Invalid or unexpected token
    
      4 | import ...;
      5 | import ...;
    > 6 | import './styles.less';
        | ^
      7 |

在 jest.config.js 文件里配置 moduleNameMapper

// jest.config.js
module.exports = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: "coverage",
    coverageProvider: "v8",
    testEnvironment: "jsdom",
+   moduleNameMapper: {
    '^.+\\.(css|less)$': 'identity-obj-proxy',
    },
}

报错二

重新执行 npm run test ,继续报错:

 Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.
          To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`
          before using any of Enzyme's top level APIs, where `Adapter` is the adapter
          corresponding to the library currently being tested. For example:

          import Adapter from 'enzyme-adapter-react-15';
 To find out more about this, see https://airbnb.io/enzyme/docs/installation/index.html

       6 |   describe('...', () => {
       7 |     it('...', () => {
    >  8 |       const wrapper = mount(<Empty />);
         |                       ^

在 jest.config.js 文件里配置 setupFilesAfterEnv

// jest.config.js
+ const path = require('path');

module.exports = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: "coverage",
    coverageProvider: "v8",
    testEnvironment: "jsdom",
    moduleNameMapper: {
    '^.+\\.(css|less)$': 'identity-obj-proxy',
    },
+   setupFilesAfterEnv: [path.resolve(__dirname, './setupAfterEnv.js')],
}

在根目录下新建 setupAfterEnv.js,或者在任何你想要的地方新建都行,但是要注意 jest.config.js 里面配置的 setupFilesAfterEnv 对应的 setupAfterEnv.js 文件的路径,请保持一致。

// setupAfterEnv.js
import Enzyme from 'enzyme';
// 我的 react 版本是 17.+,所以我使用的是 @wojtekmaj/enzyme-adapter-react-17,请保持版本一致
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

Enzyme.configure({ adapter: new Adapter() });

执行 npm run test ,测试通过~

报错三

看看其他的报错,故意 修改 jest.config.js 文件

// jest.config.js
const path = require('path');

module.exports = {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: "coverage",
    coverageProvider: "v8",
    // 把 testEnvironment 改成 node
-   testEnvironment: "jsdom",
+   testEnvironment: "node",
    moduleNameMapper: {
    '^.+\\.(css|less)$': 'identity-obj-proxy',
    },
    setupFilesAfterEnv: [path.resolve(__dirname, './setupAfterEnv.js')],
}

把 testEnvironment 从 jsdom 改成 node,看会报什么错

 It looks like you called `mount()` without a global document being loaded.

       6 |   describe('...', () => {
       7 |     it('...', () => {
    >  8 |       const wrapper = mount(<Empty />);
         |                       ^

如果你遇到这个问题,请试着把 jest.config.js 文件里的 testEnvironment 配置改为 jsdom

报错四

再试着修改一下 babel.config.js 看会导致什么报错

// babel.config.js
// 直接注释掉 presets
module.exports = {
  // presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
};

执行 npm run test , 报错如下

 Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    G:\tiny-rc\setupAfterEnv.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Enzyme from 'enzyme';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1479:14)

如果你遇到这个问题,试着在 babel.config.js 配置 presets

以上是目前遇到的全部问题。