首页 > 解决方案 > 我应该如何使用 Jest 设置 Enzyme Adapter 配置文件?

问题描述

我已经按照其他项目和线程中的说明进行操作,但无法让 React 找到 Enzyme 配置文件。

package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
"jest": {
    "collectCoverageFrom": [
      "src/**/*.{js, jsx, mjs}"
    ],
    "setupFiles": [
      "<rootDir>src/setupTests.js"
    ]
  }

src/setupTests.js

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
export { shallow, render, mount } from "enzyme";
export { shallowToJson } from "enzyme-to-json";

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

export default Enzyme;

the error when running tests

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';

任何帮助将非常感激。谢谢

标签: reactjsjestjsenzyme

解决方案


按照这个配置:

// test-setup.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

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

然后在您的笑话配置中添加一个setupFilesAfterEnv密钥并指向该文件。例如,如果您的 jest 配置位于package.json

// package.json
{
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>src/setupTests.js"]
  }
}

来自酶文档: https ://airbnb.io/enzyme/docs/guides/jest.html

运行一些代码以在每次测试之前配置或设置测试框架的模块的路径列表。由于 setupFiles 在环境中安装测试框架之前执行,因此该脚本文件为您提供了在环境中安装测试框架后立即运行一些代码的机会。


推荐阅读