我正在尝试编写一个简单的单元测试,似乎无法弄明白。我想测试一个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字段的prop modalBox,它只返回模态体的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进行浅层渲染并尝试这种方法,但没有运气。基于我在网上看到的例子以及之前的反应测试经验&lt; 0.14,我觉得这个测试应该有效。我只是不知道我错过了什么或误解了什么。在过去,我做了类似下面的事情,只是查看了componentNode对象以查找元素等,但componentNode返回null。
let component = TestUtils.renderIntoDocument(element);
let componentNode = findDOMNode(component);
感谢您的帮助!
答案 0 :(得分:0)
最终解决方案是向ModalBox组件添加ref。添加后,我们就可以像这样定位节点:
let component = TestUtils.renderIntoDocument(<ModalBox modalBox={modalBoxObj} />);
let componentNode = findDOMNode(component.refs.modalBox._modal);