【问题标题】:Cannot read property 'have' of undefined when testing Material-UI Component with Jest and Enzyme使用 Jest 和 Enzyme 测试 Material-UI 组件时无法读取未定义的属性“拥有”
【发布时间】:2019-12-24 04:11:17
【问题描述】:

我正在编写 [Storybook] 教程,但使用 Material-UI 作为 UI 框架。
我已经完成了可以使用Task 和TaskList 组件的程度。 我开始使用Jest 和enzyme 编写测试,这就是事情开始发生变化的地方。

我的测试看起来像

import React from "react";
import ReactDOM from "react-dom";
import TaskList from "./TaskList";
import { withPinnedTasks } from "../../stories/TaskList.stories";
import { MuiThemeProvider } from "@material-ui/core";
import { theme } from "../theme";
import { createMount } from "@material-ui/core/test-utils";

describe("SearchField", () => {
  let mount;
  beforeEach(() => {
    mount = createMount();
  });

  afterEach(() => {
    mount.cleanUp();
  });

  it("renders pinned tasks at the start of the list", () => {
    const div = document.createElement("div");
    const events = { onPinTask: jest.fn(), onArchiveTask: jest.fn() };

    let wrapper = mount(
      <MuiThemeProvider theme={theme}>
        <TaskList tasks={withPinnedTasks} {...events} />
      </MuiThemeProvider>
    );

    console.log(wrapper);

    // We expect the task titled "Task 6 (pinned)" to be rendered first, not at the end
    const lastTaskInput = wrapper.find('#id').to.have.lengthOf(1);

    // querySelector(
    //   '.list-item:nth-child(1) input[value="Task 6 (pinned)"]'
    // );
    expect(lastTaskInput).not.toBe(null);

    ReactDOM.unmountComponentAtNode(div);
  });
});

当我运行yarn test 时,它失败并出现以下错误


  ● SearchField › renders pinned tasks at the start of the list

    TypeError: Cannot read property 'have' of undefined

      30 |
      31 |     // We expect the task titled "Task 6 (pinned)" to be rendered first, not at the end
    > 32 |     const lastTaskInput = wrapper.find('#id').to.have.lengthOf(1);
         |                           ^
      33 |
      34 |     // querySelector(
      35 |     //   '.list-item:nth-child(1) input[value="Task 6 (pinned)"]'

      at Object.it (src/components/TaskList.test.js:32:27)

整个代码库可在https://codesandbox.io/s/github/hhimanshu/storyboook-materialui-react/tree/jest 获得

但由于这是测试失败,如果你正在寻找直接的github链接,你可以在https://github.com/hhimanshu/storyboook-materialui-react/tree/jest找到这个

我正在寻求以下方面的帮助
1. 这段代码有什么不正确的?我正在学习使用 Jest 和 enzyme 进行测试,并且很想知道我需要学习什么
2. 如何使用MuiThemeProvider 测试Material-UI 自定义主题组件。

谢谢

【问题讨论】:

  • 你没有忘记expect吗?这就是你想要测试的东西expect(wrapper.find('#id')).to.have.lengthOf(1);?

标签: reactjs jestjs material-ui enzyme storybook


【解决方案1】:

我不认为.to.have 是正确的笑话语法,我相信酶文档假设不同的测试框架?在此处查看可以在开玩笑 expect 方法调用中调用的内容

https://jestjs.io/docs/en/expect

看起来你需要类似的东西

const lastTaskInput = expect(wrapper.find('#id').length).toEqual(1);

具体从这里阅读...

https://jestjs.io/docs/en/expect#toequalvalue

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2021-10-29
    • 2021-05-19
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2018-11-27
    相关资源
    最近更新 更多