jest 学习:如何处理在 jest 测试的时候,css文件报错

有时候在组件内部有引入 .css 文件,这个时候在用 jest做测试的时候,会报错
更新于: 2021-12-19 12:57:29

示例React组件如下

import noop from '@jswork/noop';
import classNames from 'classnames';
import React, { Component } from 'react';
import './style.css'

export type ReactCopiedProps = {};
const CLASS_NAME = 'react-copied';

export default class ReactCopied extends Component<ReactCopiedProps> {
  static displayName = CLASS_NAME;
  static version = '__VERSION__';

  static defaultProps = {
    onChange: noop,
    items: ['Copy', 'Copied'],
    interval: 600
  };

  state = { index: 0 };
  // ....
}

直接测试报错如下 Jest doesn't works with JSX which imports CSS

yarn run:test v0.21.3
$ NODE_ENV=client jest -u
 FAIL  src/__tests__/app.test.js
  ● Test suite failed to run

    /home/svipben/Documents/react-boilerplate/src/client/app/app.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){body {
                                                                                                  ^
    SyntaxError: Unexpected token {

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (src/client/app/app.jsx:7:1)
      at Object.<anonymous> (src/__tests__/app.test.js:2:12)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.693s
Ran all test suites.
error Command failed with exit code 1.

解决办法

  1. jest.config.js 加入配置
  2. 建立文件 /src/__tests__/__mocks__/styleMock.js
  3. 文件内容 module.exports = {};
module.exports = {
  // The root of your source code, typically /src
  // `<rootDir>` is a token Jest substitutes
  roots: ['<rootDir>/src'],
  'moduleNameMapper': {
    '\\.(css|less)$': '<rootDir>/src/__tests__/__mocks__/styleMock.js',
  },
}

参考

https://github.com/facebook/jest/issues/3094

https://jestjs.io/docs/webpack