我尝试使用 enzyme 来模拟复选框上的 change
事件,并使用 chai-enzyme
来断言它是否已被选中。
这是我的 Hello
react 组件:
import React from 'react';
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false
}
}
render() {
const {checked} = this.state;
return <div>
<input type="checkbox" defaultChecked={checked} onChange={this._toggle.bind(this)}/>
{
checked ? "checked" : "not checked"
}
</div>
}
_toggle() {
const {onToggle} = this.props;
this.setState({checked: !this.state.checked});
onToggle();
}
}
export default Hello;
我的测试:
import React from "react";
import Hello from "../src/hello.jsx";
import chai from "chai";
import {mount} from "enzyme";
import chaiEnzyme from "chai-enzyme";
import jsdomGlobal from "jsdom-global";
import spies from 'chai-spies';
function myAwesomeDebug(wrapper) {
let html = wrapper.html();
console.log(html);
return html
}
jsdomGlobal();
chai.should();
chai.use(spies);
chai.use(chaiEnzyme(myAwesomeDebug));
describe('<Hello />', () => {
it('checks the checkbox', () => {
const onToggle = chai.spy();
const wrapper = mount(<Hello onToggle={onToggle}/>);
var checkbox = wrapper.find('input');
checkbox.should.not.be.checked();
checkbox.simulate('change', {target: {checked: true}});
onToggle.should.have.been.called.once();
console.log(checkbox.get(0).checked);
checkbox.should.be.checked();
});
});
当我运行此测试时,checkbox.get(0).checked
为 false
,并且断言 checkbox.should.be.checked()
报告错误:
AssertionError: expected the node in <Hello /> to be checked <input type="checkbox" checked="checked">
您可以看到该消息非常奇怪,因为输出中已经有 checked="checked"
。
我不知道哪里错了,因为涉及的东西太多了。
您还可以在此处查看演示项目:https://github.com/js-demos/react-enzyme-simulate-checkbox-events-demo ,通知these lines
最佳答案
我认为我的解释的一些细节可能有点错误,但我的理解是:
当你这样做时
var checkbox = wrapper.find('input');
它会在 checkbox
中保存对该 Enzyme 节点的引用,但有时当 Enzyme 树更新时,checkbox
却没有更新。我不知道这是否是因为树中的引用发生了变化,因此 checkbox
现在是对旧版本树中节点的引用。
使 checkbox
成为一个函数似乎对我有用,因为现在 checkbox()
的值总是从最新的树中获取。
var checkbox = () => wrapper.find('input');
checkbox().should.not.be.checked();
checkbox().simulate('change', {target: {checked: true}});
///...
关于reactjs - 使用 enzyme 模拟 `checked` 后,复选框不是 `change`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892256/