当 Ant Design 和 Jest 一起使用的时候,在某些情况下(开启 coverage 的时候)会导致单元测试运行失败。一个可能造成问题的 Ant Design 代码如下:
import { Input } from 'antd';
const { TextArea } = Input;Jest 会报错:
ReferenceError: Input is not defined
  1 | import { Input } from 'ant-design';
  2 |
> 3 | const { TextArea } = Input;报错的直接原因,是使用了 Ant Design 推荐的 babel-plugin-import 和 Jest 计算 coverage 使用的 babel-plugin-istanbul 造成的。在这里、这里等 GitHub Issue 中都有相应的讨论。
要修复这个问题,只需要在 Jest 或者单元测试环境中,不使用 babel-plugin-import 这个转换插件就可以了。参考代码如下,在 .babelrc 中:
{
  "env": {
    "development": {
      "plugins": [
        [
          "import",
          {
            "libraryName": "antd",
            "style": true
          }
        ]
      ]
    },
    "production": {
      // same as above
    }
  },
  "plugins": [
    // rest of plugins...
  ]
}如此一来,只有在 NODE_ENV 为 production 或 development 的情况下,Babel 才会启用 babel-plugin-import 这个转换插件。对于 Jest 来说,因为默认设置了环境变量 NODE_ENV 为 test,所以 Plugin 不会起效。
这样造成的问题是 Jest 的运行速度会有所降低。