The checkbox is not “checked” after simulating a “change” with the enzyme

I tried to use the enzyme to simulate the event changeon the checkbox and use chai-enzymeto confirm if it was checked.

This is my react component 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;

And my test:

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

});

When I run this test, it checkbox.get(0).checkedis equal false, and the statement checkbox.should.be.checked()reports an error:

AssertionError: expected the node in <Hello /> to be checked <input type="checkbox" checked="checked">

You can see that the message is rather strange, since there is already an output checked="checked".

I’m not sure where something is wrong, because there are too many things in it.

You can also see the demo project here: https://github.com/js-demos/react-enzyme-simulate-checkbox-events-demo , pay attention to these lines

+14
2

, , :

var checkbox = wrapper.find('input');

Enzyme node checkbox, , Enzyme , checkbox - . , , , checkbox node .

checkbox, , , checkbox() .

var checkbox = () => wrapper.find('input');
checkbox().should.not.be.checked();
checkbox().simulate('change', {target: {checked: true}});
///...
+14

, " ".

, API.

Simulate dom, , , , , .

(https://github.com/facebook/react/issues/4950), , dom React , , , - , ..

- dom API- .

+6

Source: https://habr.com/ru/post/1656912/


All Articles