isVisible在使用jest-dom的Jest测试中不起作用

时间:2020-06-17 11:22:22

标签: javascript reactjs jestjs enzyme testing-library

Edit check-checkbox-hidden-with-jsdom

我尽可能简化地创建了一个CodeSandbox,以重现我的问题。您可以在CodeSandbox中看到运行失败的测试。

在我的示例中,我有一个名为MyCheckbox的组件,它只是一个材质用户界面Checkbox的包装。它需要一个道具data,它只是一个数组。如果数组中包含某些内容,则复选框将获得opacity : 1,否则将获得opacity : 0

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的实例,以便一个可见,另一个不可见。

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>
  );
}

....这将在浏览器中显示以下内容

enter image description here

然后我有一个简单的测试,检查第一个复选框是否已隐藏,第二个复选框是否可见

import React from "react";

import Enzyme, { mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "@testing-library/jest-dom";
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).find('input[type="checkbox"]');
  expect(checkboxes).toHaveLength(2);


  expect(checkboxes.at(0).getDOMNode()).not.toBeVisible();
  //This checkbox is in fact visible but the following test step is failing ??
  expect(checkboxes.at(1).getDOMNode()).toBeVisible();
});

即使第二个复选框清晰可见,测试也会失败并显示以下错误。这是jestjest-dom中的错误吗?

expect(element).toBeVisible()

Received element is not visible:
  <input class="PrivateSwitchBase-input-5" data-indeterminate="false" type="checkbox" value="" />

0 个答案:

没有答案