使用CRA为响应应用配置笑话和酶

时间:2019-11-28 07:34:56

标签: reactjs jestjs enzyme

我已经使用CRA构建了一个样例react应用程序,我正在尝试为该应用程序编写单元测试。

使用开玩笑,酶,我已经安装了必需的软件包作为dev依赖项

    "enzyme": "^3.10.0",
    "enzyme-adapter-react-16": "^1.15.1",
    "jest": "^24.9.0"

jest.config.js -位于 src 文件夹的外部

module.exports = {
    verbose: true,
    setupFilesAfterEnv: ["./src/setupTest.js"],
};

setupTest.js -在 src 文件夹根目录

内部

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

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

App.test.js

import React from "react";
import { shallow } from "enzyme";

import App from "./App";

describe("<App />", () => {
    it("Renders the app component", () => {
        const wrapper = shallow(<App />);
        expect(wrapper).toMatchSnapshot();
    });
});

当我尝试进行 npm运行测试时,出现以下错误。

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 http://airbnb.io/enzyme/docs/installation/index.html

   6 | describe("<App />", () => {
   7 |     it("Renders the app component", () => {
>  8 |         const wrapper = shallow(<App />);
     |                         ^
   9 |         expect(wrapper).toMatchSnapshot();
  10 |     });
  11 | });

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您必须将 setupFilesAfterEnv 文件命名为 src/setupTests.jssrc/setupTests.ts。如果不从 create-react-app 中弹出,则无法使用此配置。

这是 CRA 的功能设置文件:

src/setupTests.js

(注意文件名中是 setupTests 而不是 setupTest

import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

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

More information

答案 1 :(得分:0)

我认为您的文件名中有错字,您忘记在文件名末尾(setupTests)添加 s ,安装文件的预期路径为public Type GetListItemType<T>(List<T> list) { Type type = list.GetType(); while (type != typeof(List<T>)) type = type.BaseType; return type.GetGenericArguments().Single(); } var list = new List<int>(); var subList = new SubList(); Console.WriteLine(GetListItemType(list)); // System.Int32 Console.WriteLine(GetListItemType(subList)); // System.Int32

您也可以使用此文件名,但是必须将其包含在如下所示的jest配置中。

src/setupTests.js

希望这会有所帮助