使用Jest测试React Component函数
Test a React Component function with Jest
原件
首先,我遵循Flux架构。
我有一个显示秒数的指示器,例如:30秒。每隔一秒,它就会显示少1秒,所以29、28、27直到0。当到达0时,我清除间隔,使其停止重复。此外,我触发了一个动作。当这个操作被调度时,我的商店会通知我。所以当这种情况发生时,我会将间隔重置为30秒等等。组件看起来像:
var Indicator = React.createClass({
mixins: [SetIntervalMixin],
getInitialState: function(){
return{
elapsed: this.props.rate
};
},
getDefaultProps: function() {
return {
rate: 30
};
},
propTypes: {
rate: React.PropTypes.number.isRequired
},
componentDidMount: function() {
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
MyStore.removeChangeListener(this._onChange);
},
refresh: function(){
this.setState({elapsed: this.state.elapsed-1})
if(this.state.elapsed == 0){
this.clearInterval();
TriggerAnAction();
}
},
render: function() {
return (
<p>{this.state.elapsed}s</p>
);
},
/**
* Event handler for 'change' events coming from MyStore
*/
_onChange: function() {
this.setState({elapsed: this.props.rate}
this.setInterval(this.refresh, 1000);
}
});
module.exports = Indicator;
组件按预期工作。现在,我想和Jest一起测试一下。我知道我可以使用renderIntoDocument,然后我可以将Timeout设置为30s,并检查我的component.state.elaped是否等于0(例如)。
但是,我想在这里测试的是不同的东西。我想测试是否调用了刷新函数。此外,我想测试一下,当我的运行状态为0时,会触发我的TriggerAnAction()。好吧,我试着做的第一件事:
jest.dontMock('../Indicator');
describe('Indicator', function() {
it('waits 1 second foreach tick', function() {
var React = require('react/addons');
var Indicator = require('../Indicator.js');
var TestUtils = React.addons.TestUtils;
var Indicator = TestUtils.renderIntoDocument(
<Indicator />
);
expect(Indicator.refresh).toBeCalled();
});
});
但我在写npm测试时收到以下错误:
Throws: Error: toBeCalled() should be used on a mock function
我从ReactTestUtils中看到了一个mockComponent函数,但给出了它的解释,我不确定它是否是我需要的。
好吧,在这一点上,我被卡住了。有人能告诉我如何测试我上面提到的两件事吗?
更新1,基于Ian的回答
这就是我正在尝试运行的测试(请参阅某些行中的注释):
jest.dontMock('../Indicator');
describe('Indicator', function() {
it('waits 1 second foreach tick', function() {
var React = require('react/addons');
var Indicator = require('../Indicator.js');
var TestUtils = React.addons.TestUtils;
var refresh = jest.genMockFunction();
Indicator.refresh = refresh;
var onChange = jest.genMockFunction();
Indicator._onChange = onChange;
onChange(); //Is that the way to call it?
expect(refresh).toBeCalled(); //Fails
expect(setInterval.mock.calls.length).toBe(1); //Fails
// I am trying to execute the 1 second timer till finishes (would be 60 seconds)
jest.runAllTimers();
expect(Indicator.state.elapsed).toBe(0); //Fails (I know is wrong but this is the idea)
expect(clearInterval.mock.calls.length).toBe(1); //Fails (should call this function when time elapsed is 0)
});
});
我还是有点误会。。。
看起来你走在了正确的轨道上。为了确保每个人都对这个答案持一致意见,让我们去掉一些术语。
模拟:一个行为由单元测试控制的函数。您通常用mock函数交换某个对象上的实际函数,以确保mock函数被正确调用。Jest自动为模块上的每个函数提供mock,除非您对该模块的名称调用jest.dontMock
。
组件类:这是React.createClass
返回的东西。您可以使用它来创建组件实例(它比这更复杂,但这足以满足我们的目的)。
组件实例:组件类的实际渲染实例。这是调用TestUtils.renderIntoDocument
或许多其他TestUtils
函数后得到的结果。
在问题的更新示例中,您生成mock并将其附加到组件类,而不是组件的实例。此外,您只想模拟出要监视或以其他方式更改的函数;例如,您对_onChange
进行了模拟,但实际上并不想这样做,因为您希望它表现正常——您只想对refresh
进行模拟。
以下是我为这个组件编写的一组建议的测试;评论是内联的,所以如果你有任何问题,请发表评论。此示例和测试套件的完整工作源位于https://github.com/BinaryMuse/so-jest-react-mock-example/tree/master;您应该能够克隆它并毫无问题地运行它。请注意,我不得不对组件进行一些小的猜测和更改,因为并非所有引用的模块都在您最初的问题中。
/** @jsx React.DOM */
jest.dontMock('../indicator');
// any other modules `../indicator` uses that shouldn't
// be mocked should also be passed to `jest.dontMock`
var React, IndicatorComponent, Indicator, TestUtils;
describe('Indicator', function() {
beforeEach(function() {
React = require('react/addons');
TestUtils = React.addons.TestUtils;
// Notice this is the Indicator *class*...
IndicatorComponent = require('../indicator.js');
// ...and this is an Indicator *instance* (rendered into the DOM).
Indicator = TestUtils.renderIntoDocument(<IndicatorComponent />);
// Jest will mock the functions on this module automatically for us.
TriggerAnAction = require('../action');
});
it('waits 1 second foreach tick', function() {
// Replace the `refresh` method on our component instance
// with a mock that we can use to make sure it was called.
// The mock function will not actually do anything by default.
Indicator.refresh = jest.genMockFunction();
// Manually call the real `_onChange`, which is supposed to set some
// state and start the interval for `refresh` on a 1000ms interval.
Indicator._onChange();
expect(Indicator.state.elapsed).toBe(30);
expect(setInterval.mock.calls.length).toBe(1);
expect(setInterval.mock.calls[0][1]).toBe(1000);
// Now we make sure `refresh` hasn't been called yet.
expect(Indicator.refresh).not.toBeCalled();
// However, we do expect it to be called on the next interval tick.
jest.runOnlyPendingTimers();
expect(Indicator.refresh).toBeCalled();
});
it('decrements elapsed by one each time refresh is called', function() {
// We've already determined that `refresh` gets called correctly; now
// let's make sure it does the right thing.
Indicator._onChange();
expect(Indicator.state.elapsed).toBe(30);
Indicator.refresh();
expect(Indicator.state.elapsed).toBe(29);
Indicator.refresh();
expect(Indicator.state.elapsed).toBe(28);
});
it('calls TriggerAnAction when elapsed reaches zero', function() {
Indicator.setState({elapsed: 1});
Indicator.refresh();
// We can use `toBeCalled` here because Jest automatically mocks any
// modules you don't call `dontMock` on.
expect(TriggerAnAction).toBeCalled();
});
});
我想我理解你的要求,至少部分理解!
从错误开始,您之所以看到这一点,是因为您已指示jest不要模拟Indicator模块,因此所有内部内容都与您编写的一样。如果你想测试调用了哪个特定的函数,我建议你创建一个mock函数并使用它。。。
var React = require('react/addons');
var Indicator = require('../Indicator.js');
var TestUtils = React.addons.TestUtils;
var refresh = jest.genMockFunction();
Indicator.refresh = refresh; // this gives you a mock function to query
接下来要注意的是,您实际上在示例代码中重新分配了Indicator变量,因此为了正确的行为,我将第二个变量重命名为(如下所示)
var indicatorComp = TestUtils.renderIntoDocument(<Indicator />);
最后,如果您想测试随时间变化的东西,请围绕计时器操作使用TestUtils功能(http://facebook.github.io/jest/docs/timer-mocks.html)。在你的情况下,我认为你可以做到:
jest.runAllTimers();
expect(refresh).toBeCalled();
或者,也许不那么挑剔的是,依靠setTimeout和setInterval的模拟实现来推断您的组件:
expect(setInterval.mock.calls.length).toBe(1);
expect(setInterval.mock.calls[0][1]).toBe(1000);
另一件事是,要使上述任何更改生效,我认为您需要手动触发onChange方法,因为您的组件最初将使用模拟版本的Store,因此不会发生更改事件。您还需要确保您已将jest设置为忽略react模块,否则它们也会被自动嘲笑。
完整建议测试
jest.dontMock('../Indicator');
describe('Indicator', function() {
it('waits 1 second for each tick', function() {
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var Indicator = require('../Indicator.js');
var refresh = jest.genMockFunction();
Indicator.refresh = refresh;
// trigger the store change event somehow
expect(setInterval.mock.calls.length).toBe(1);
expect(setInterval.mock.calls[0][1]).toBe(1000);
});
});
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 将函数的上下文应用于javascript变量
- 如何在JavaScript中将字符串转换为函数引用
- 用嵌套函数和默认函数定义函数
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 无法导出函数expressjs/requestjs中的变量
- 函数参数中的数据与指定变量之间的任何性能差异
- JQuery合并了keyup和focusout两个函数
- ES6构造函数返回基类的实例
- 监视函数从服务返回不起作用,但作用域函数起作用
- 我可以在json对象中添加一个函数吗
- AngularJS:我可以跳过函数参数回调吗
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- Angular 2 Component自定义属性在构造函数中为null
- Angular 1.5 component vs.old directive-其中是链接函数
- 使用Jest测试React Component函数
- 把AngularJS 2的Component当作element属性中的函数来使用
- 使用js函数设置Composite Component属性
- AngularJS .component()中的输出函数('&')不起作用