用酶模拟`变化`后,复选框未被‘选中’ [英] Checkbox is not `checked` after simulate `change` with enzyme

查看:15
本文介绍了用酶模拟`变化`后,复选框未被‘选中’的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用酶来模拟复选框上的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;

我的测试:

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).checkedfalse,而断言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中保存了对该酶节点的引用,但有时酶树会更新,但checkbox不会。我不知道这是否是因为树中的引用发生了更改,因此checkbox现在是对树的旧版本中的节点的引用。

创建checkbox函数似乎使其适用于我,因为现在checkbox()的值始终取自最新的树。

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

这篇关于用酶模拟`变化`后,复选框未被‘选中’的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆