如何在Enzyme Jest Test中切换和选中一个材料UI复选框?

问题描述 投票:0回答:1

我有一个简单的组件,包裹着一个Material UI复选框。我在这里把它简化到最低限度。

//@flow
import React from "react";
import { Checkbox } from "@material-ui/core";

function MyCheckboxComponent() {
  const [checkedState, setCheckedState] = React.useState(true);

  const handleChange = event => {
    setCheckedState(event.target.checked);
  };

  return <Checkbox checked={checkedState} onChange={handleChange} />;
}

export default MyCheckboxComponent;

我只是想测试这个组件,然后切换Checkbox的值并选中它。我无法让我的简单测试通过。我不知道为什么。

import React from "react";

import Enzyme, { mount } from "enzyme";
import { Checkbox } from "@material-ui/core";
import Adapter from "enzyme-adapter-react-16";

import MyCheckboxComponent from "./MyCheckboxComponent";
Enzyme.configure({ adapter: new Adapter() });

/** Interaction tests testing user interaction with PilzButton */
test("Toggle Checkbox test", () => {
  const wrapper = mount(<MyCheckboxComponent />);

  const checkBox = wrapper.find(Checkbox);
  expect(checkBox).toHaveLength(1);

  checkBox.simulate('change', { target: { checked: true } });

  expect(checkBox.props().checked).toBe(true);
});

应该 checkBox.simulate('change', { target: { checked: true } }); 的值,并切换 Checkbox ??

到目前为止,我在CodeSandbox上有什么......

Edit toggle-material-ui-checkbox-jest

javascript reactjs checkbox jestjs enzyme
1个回答
1
投票

最新版本的酶会缓存从以下地方返回的结果 find 和其他方法。

你需要重新找到并也使用 .update() 来强制刷新状态重新渲染。

  const checkBox = wrapper.find(Checkbox);
  expect(checkBox).toHaveLength(1);

  checkBox.simulate('change', { target: { checked: true } });

  wrapper.update();

  expect(wrapper.find(Checkbox).props().checked).toBe(true);

另外,这可能只是因为你想产生一个最小的可重复性问题,但你的测试目前很差,因为你的默认值是true,而你是动态传递true进来的。

你应该这样做,而不是。

  const checkBox = wrapper.find(Checkbox);
  expect(checkBox).toHaveLength(1);
  expect(checkBox.props().checked).toBe(true);

  checkBox.simulate('change', { target: { checked: false } });

  wrapper.update();

  expect(wrapper.find(Checkbox).props().checked).toBe(false);

这个测试实际上是在证明 onChange 现在可以正常工作了。

© www.soinside.com 2019 - 2024. All rights reserved.