我有这个组成部分:
import React, {useState} from 'react';
const Checkbox = () => {
const [checked, setChecked] = useState(false);
return (
<div>
<input onChange={()=> setChecked(!checked)} type="checkbox"/>
</div>
);
};
export default Checkbox;
现在,我想检查是否单击输入,状态是否正在更改。 为此,我做到了:
import React from "react";
import { shallow, configure, mount } from 'enzyme';
import Checkbox from "./Checkbox";
import Adapter from 'enzyme-adapter-react-16'
configure({adapter: new Adapter()});
it('should render checkbox', () => {
const component = shallow(<Checkbox />);
const btn = component.find('input');
btn.simulate('click');
...
});
现在,我无法弄清楚如何完成测试。谁可以帮忙?
答案 0 :(得分:1)
点击后,您可以使用以下命令检查该复选框是否已选中
it('toggles checked state', () => {
const component = shallow(<Checkbox />);
const btn = component.find('input');
btn.simulate('click');
const checkbox = component.find({ type: 'checkbox' });
expect(checkbox.props().checked).to.equal(true);
});
编辑: 由于我的原始答案有效,但我想给出更多的解释,但不符合预期。
您正在定义checked
状态,因此我假设您想使其成为检查/取消选中复选框的唯一事实来源。
但是,此复选框目前不受控制。这意味着它已使用HTML API进行了检查/取消检查,并且与您定义的checked
状态无关。
如果希望此checked
状态控制复选框,则需要将checked
属性添加到输入中:
<input onChange={()=> setChecked(!checked)} type="checkbox" checked={checked} />
通过这种方式,该复选框由React组件的状态控制。
Ref:https://fr.reactjs.org/docs/forms.html#controlled-components