如何访问React中的方法进行单元测试 [英] How do I access methods in React for unit testing
问题描述
我有一个非常困难的时间用React测试任何东西。 TestUtils上的文档很稀疏,没有例子。谷歌似乎只给我一些结果。我正在使用Jasmine,但这并不是让我感到悲痛的部分。
I'm having an incredibly difficult time unit testing anything with React. The docs on TestUtils are sparse and there's no examples. Google seems to only be giving me a couple results. I'm using Jasmine, but that's not really the part that's giving me grief.
这是我尝试过的最简单的事情:
Here's the simplest thing I've tried testing:
var BigButton = React.createClass({
render: function () {
return (
<button className="big-submit" data-color={this.props.color} onClick={this.props.action}>{this.props.text}</button>
);
},
foo: function () {},
bar: function () {
this.foo();
}
});
我有一个测试
describe('BigButton', function () {
describe('render', function () {
it('creates a button', function () {
var button = <BigButton />;
TestUtils.renderIntoDocument(button);
debugger;
});
});
});
我的问题是如何从外部访问React类中有意义的任何内容?我如何检查渲染是否返回按钮HTML元素?我知道如何使用测试间谍,但我怎么能找到方法 foo
进行间谍活动以及如何调用 bar
?似乎所有东西都以一种完全不可测试的方式被包裹起来。
My question is how do I access anything meaningful in a React class from the outside? How do I even check if render returns a button HTML element? I know how to use testing spies, but how do I even find the method foo
to spy on and how do I call bar
? Everything seems to be somehow wrapped up in a way that's completely untestable.
推荐答案
我不知道你是否知道,但Facebook写了自己的基于Jasmine的测试库: https://facebook.github.io/jest
I don't know if you're aware, but Facebook wrote it's own testing library built upon Jasmine: https://facebook.github.io/jest
他们在这里有一个测试反应教程: https://facebook.github.io/ jest / docs / tutorial-react.html
They have a tutorial for testing react here: https://facebook.github.io/jest/docs/tutorial-react.html
我认为这是如何使用TestUtils的一个很好的例子,即使你不想用开玩笑。要点是:
I think this is a good example on how to work with TestUtils, even if you don't want to use jest. The main points are:
-
renderIntoDocument()
返回对分离DOM的引用节点 - 您使用的助手如
findRenderedDOMComponentWithTag()
(参见 TestUtils )从组件中获取对子节点的引用 - 你可以使用
关于断言的引用的getDOMNode()
renderIntoDocument()
returns a reference to a detached DOM node- you use helpers like
findRenderedDOMComponentWithTag()
(see TestUtils) to get references to subnodes out of your component - you can use
getDOMNode()
on your reference for assertions
这篇关于如何访问React中的方法进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!