React/Jasmine/Karma/Phantom 单元测试:findDOMNode 和 renderIntoDocument 未按预期工作

React/Jasmine/Karma/Phantom Unit Test: findDOMNode and renderIntoDocument not working as expected

我正在尝试编写一个简单的单元测试,但似乎无法弄明白。我想测试一个 bootstrap 模式,以确保在我将某些对象属性传递给它时它显示正确的内容。这是我的模态代码:

import React, { Component, PropTypes } from 'react';
import { Button, Modal } from 'react-bootstrap';

class ModalBox extends Component {
  render() {
    const { modalBox } = this.props;
    let content;

    if (modalBox.contentBody) {
      content = modalBox.contentBody;
    } else {
      content = (
        <span>
          <Modal.Header closeButton onHide={this.close.bind(this)}>
            <Modal.Title>{modalBox.title}</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            {modalBox.message}
          </Modal.Body>
          {modalBox.isConfirm &&
            <Modal.Footer>
              <Button onClick={modalBox.onCancel} className="modal-button cancel">{modalBox.cancelText || 'Cancel'}</Button>
              <Button onClick={modalBox.onConfirm} className="modal-button confirm">{modalBox.confirmText || 'Confirm'}</Button>
            </Modal.Footer>
          }
        </span>
      );
    }

    return (
      <Modal show={typeof modalBox != 'undefined'} onHide={this.close.bind(this)} dialogClassName={modalBox.dialogClassName || ''} backdrop={modalBox.backdrop || true}>
        {content}
      </Modal>
    );
  }
}

所以为了测试,我想确保如果我传递包含 contentBody 字段的 modalBox 道具,它只是 returns 模态主体的 contentBody。这是我要测试的示例:

it("renders only contentBody when provided", () => {
let modalBoxObj = {
  contentBody: <div className="test-content-body">This is a test.</div>
};

let element = React.createElement(ModalBox, {modalBox: modalBoxObj});

let component = TestUtils.renderIntoDocument(element);
let modalWrapper = TestUtils.scryRenderedDOMComponentsWithClass(component, 'modal');

// modalWrapper returns an empty array, so this returns "Expected 0 to be 1"
expect(modalWrapper.length).toBe(1);

let testBody = TestUtils.scryRenderedDOMComponentsWithClass(component, 'test-content-body');


// testBody returns an empty array, so this returns "Expected 0 to be 1"
expect(testBody.length).toBe(1);

// this returns "TypeError: 'undefined' is not an object (evaluating 'testBody[0].innerHTML')"
expect(testBody[0].innerHTML).toEqual("This is a test.");
}

我也尝试过使用 TestUtils.createRenderer 进行浅渲染并尝试这种方法,但没有成功。根据我在网上看到的例子和之前react <0.14的测试经验,我觉得这个测试应该可以。我只是不知道我遗漏了什么或误解了什么。过去,我做了类似下面的事情,只是查看 componentNode 对象来查找元素等,但是 componentNode 返回 null。

let component = TestUtils.renderIntoDocument(element);
let componentNode = findDOMNode(component);

感谢您的帮助!

最终的解决方案是向 ModalBox 组件添加一个 ref。添加后,我们可以像这样定位节点:

let component = TestUtils.renderIntoDocument(<ModalBox modalBox={modalBoxObj} />);
let componentNode = findDOMNode(component.refs.modalBox._modal);