【问题标题】:How can Enzyme check for component visibility?Enzyme 如何检查组件的可见性?
【发布时间】:2020-10-05 23:10:04
【问题描述】:

我附上了我遇到的问题的精简版。我有一个简单的Checkbox,我使用opacity : 0 隐藏它,具体取决于传递给包含Checkbox 的组件的内容(在本例中为MyCheckbox

MyCheckBox.js

import React from "react";
import "./styles.css";
import { Checkbox, makeStyles } from "@material-ui/core";

const useStyles = makeStyles({
  checkboxHiddenStyle: {
    opacity: 0
  }
});

export default function MyCheckbox(props) {
  const styles = useStyles(props);
  return (
    <div>
      <Checkbox
        {...props}
        className={props.data.length === 0 && styles.checkboxHiddenStyle}
      />
    </div>
  );
}

我有一个使用 MyCheckbox 的组件,称为 MyCheckboxesInUse,这会导致一个复选框显示而另一个被隐藏。

如何在 Jest/Enzyme 测试中检查每一项的可见性?我看了很多帖子,但找不到有用的东西!

在 CodeSandbox 上运行的代码和测试

MyCheckBoxesInUse.js

import React from "react";
import MyCheckbox from "./MyCheckbox";
import "./styles.css";

export default function MyCheckboxesInUse() {
  const arrayWithNothing = [];
  const arrayWithSomething = [1];
  return (
    <div className="App">
      <h1>Hidden Checkbox</h1>
      <MyCheckbox data={arrayWithNothing} />
      <h1>Visible Checkbox</h1>
      <MyCheckbox data={arrayWithSomething} />
    </div>
  );
}

MyCheckbox.test.js

import React from "react";

import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import MyCheckboxesInUse from "./MyCheckboxesInUse";
import MyCheckbox from "./MyCheckbox";

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

test("Check that one checkbox is hidden and the other is visible", () => {
  const wrapper = mount(<MyCheckboxesInUse />);

  const checkboxes = wrapper.find(MyCheckbox);
  expect(checkboxes).toHaveLength(2);

  //HOW DO I CHECK THAT ONE IS VISIBLE AND THE OTHER IS NOT ?
});

【问题讨论】:

    标签: javascript reactjs jestjs material-ui enzyme


    【解决方案1】:

    您可以从testing-library 试用jest-dom,但如果您想看看他们如何实现您想要的,请查看他们的代码:https://github.com/testing-library/jest-dom/blob/master/src/to-be-visible.js

    【讨论】:

    • 谢谢。看起来像我需要的。当我尝试它时,我得到 expect(...).not.toBeVisible 不是一个函数。在此处查看更新的 CodeSandbox ---> codesandbox.io/s/…
    猜你喜欢
    • 2019-08-18
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2011-01-10
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多