用酶模拟"更改"后,复选框不会被"检查"

Fre*_*ind 14 checkbox simulate reactjs enzyme chai-enzyme

我尝试使用酶来模拟change复选框上的事件,并使用chai-enzyme断言是否已经检查过.

这是我的Hello反应组件:

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;
Run Code Online (Sandbox Code Playgroud)

我的测试:

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

});
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,checkbox.get(0).checkedis false,并且断言checkbox.should.be.checked()报告错误:

AssertionError: expected the node in <Hello /> to be checked <input type="checkbox" checked="checked">
Run Code Online (Sandbox Code Playgroud)

您可以看到消息很奇怪,因为checked="checked"输出中已有消息.

我不确定哪里出错,因为它涉及太多事情.

您还可以在此处查看演示项目:https://github.com/js-demos/react-enzyme-simulate-checkbox-events-demo,注意这些行

rog*_*iog 14

我认为我的解释的一些细节可能有点不对,但我的理解是:

当你这样做

var checkbox = wrapper.find('input');
Run Code Online (Sandbox Code Playgroud)

它保存了对该酶节点的引用checkbox,但有时候,当酶树更新时,却checkbox没有.我不知道这是否是因为树中的引用发生了变化,因此checkbox现在是对旧版本树中节点的引用.

制作checkbox一个功能似乎使其为我工作,因为现在的价值checkbox()总是从最带到了枣树.

var checkbox = () => wrapper.find('input');
checkbox().should.not.be.checked();
checkbox().simulate('change', {target: {checked: true}});
///...
Run Code Online (Sandbox Code Playgroud)


mas*_*dus 6

Funnny,我在尝试编写完全相同的测试时遇到了完全相同的问题:)

我也在四处寻找它,即使不是很满意,我找到的答案也很清楚.

它不是bug,而是"它按设计工作".

酶底层使用反应测试工具与反应相互作用,特别是与模拟api相互作用.

模拟实际上并不更新dom,它只是触发附加到组件的反应事件处理程序,可能还有您传入的其他参数.

根据我在这里得到的答案(https://github.com/facebook/react/issues/4950),这是因为更新dom需要React重新实现许多浏览器功能,可能仍会导致无法预料的行为,所以他们决定只依靠浏览器来进行更新.

实际测试这个的唯一方法是自己手动更新dom然后调用模拟api.