测试React Modal组件

use*_*856 5 javascript unit-testing bootstrap-modal reactjs react-jsx

对不起,我一直在努力尝试通过点击按钮来关闭我的React Modal.Modal尽可能简单,我已经尝试了我能想到或发现的一切,但我仍然无法查询它的孩子.

模态组件:

var React = require('react');
var Modal = require('react-bootstrap').Modal;
var Button = require('react-bootstrap').Button;

var MyModal = React.createClass({
  ...
  render: function() {
    return (
      <Modal className="my-modal-class" show={this.props.show}>
        <Modal.Header>
          <Modal.Title>My Modal</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Hello, World!
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.props.onHide}>Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

我的目标是测试onHide()单击" 关闭"按钮是否在单击时触发该功能.

我的测试文件:

describe('MyModal.jsx', function() {
  it('tests the Close Button', function() {
    var spy = sinon.spy();
    var MyModalComponent = TestUtils.renderIntoDocument(
      <MyModal show onHide={spy}/>
    );

    // This passes
    TestUtils.findRenderedComponentWithType(MyModalComponent, MyModal);

    // This fails
    var CloseButton = TestUtils.findRenderedDOMComponentWithTag(MyModalComponent, 'button');

    // Never gets here
    TestUtils.Simulate.click(CloseButton);
    expect(spy.calledOnce).to.be.true;
  });
});
Run Code Online (Sandbox Code Playgroud)

无论我尝试什么,我似乎无法找到关闭按钮.

Mar*_*ime 7

我使用React Base Fiddle(JSX)编写了一个jsFiddle,以了解测试中发生了什么(我创建了自己的"间谍",只需在调用时登录到控制台).

我发现你找不到你的按钮的原因是因为它不存在你可能想到的地方.

所述引导模态分量(<Modal/>)实际上被包含在内阵营叠加层模态分量(称为BaseModal在代码,这是从在这里).这反过来又使得一个调用的组件Portal,其渲染方法简单地返回null.null您正在尝试查找渲染组件的这个值.

由于模态没有被渲染为传统的React方式,React无法看到模态以便使用TestUtils.一个完全独立的<div/>子节点放在document体内,这个新节点<div/>用于构建模态.

因此,为了允许您使用React模拟单击TestUtils(按钮上的单击处理程序仍然绑定到按钮的单击事件),您可以使用标准JS方法来搜索DOM.设置您的测试如下:

describe('MyModal.jsx', function() {
  it('tests the Close Button', function() {
    var spy = sinon.spy();
    var MyModalComponent = TestUtils.renderIntoDocument(
      <MyModal show onHide={spy}/>
    );

    // This passes
    TestUtils.findRenderedComponentWithType(MyModalComponent, MyModal);

    // This will get the actual DOM node of the button
    var closeButton = document.body.getElementsByClassName("my-modal-class")[0].getElementsByClassName("btn btn-default")[0];

    // Will now get here
    TestUtils.Simulate.click(CloseButton);
    expect(spy.calledOnce).to.be.true;
  });
});
Run Code Online (Sandbox Code Playgroud)

该函数getElementsByClassName返回该类的元素集合,因此您必须从每个集合中获取第一个元素(在测试用例中,您唯一的元素).

您的测试现在应该通过^ _ ^