你真的要求测试两个不同的东西:
-
mapToProps 会像您怀疑的那样调用您的操作助手
- 当触发事件时,将调用作为 props 传递的事件处理程序
对于这些简单的函数,我看不到执行 #1 的价值,无论如何,为了单独测试 mapToProps,您需要能够注入其定义中使用的函数才能进行测试他们叫。这样做需要查看更多代码。
或者,假设动作创建者函数来自另一个模块,您可以使用link seam 拦截对动作创建者模块的调用,并用您自己的替换返回值。
使用proxyquire,您的测试可能如下所示:
const sinon = require('sinon');
let fakeActions;
let MyComponent, mapToProps;
function setupFakeActions() {
fakeActions = {
fetchPaymentDetails: sinon.stub(),
/* etc ... */
};
const module = proxyquire('../src/my-component', {
'./actions': fakeActions
});
{MyComponent, mapToProps} = module;
}
describe('MyComponent propmapping', ()=> {
setupFakeActions();
it('should create a function that dispatches actions', () => {
const dispatchStub = sinon.stub();
const result = mapToProps(dispatchStub);
result.fetchPaymentDetails();
assert(dispatchStub.calledOnce);
assert(fakeActions.fetchPaymentDetails.calledOnce);
// more assertions: http://sinonjs.org/releases/v2.3.4/assertions/
assert(dispatchStub.calledWith(fakeActions.fetchPaymentDetails));
});
});
您尚未使用 redux 标记您的问题,但假设您使用它,还有另一种方法可以测试函数是否执行它们应该执行的操作,当然就是创建一个商店,触发操作,然后查看如果正确的结果来自商店,但在意图和实施上相当模糊,因此不推荐。
现在,第二点更有价值,使用Enzyme 非常直接:
/* assuming existing test setup code for Mocha is in place: describe, it, ... */
it('calls assigned props on click events', () => {
const props = {};
props.fetchPaymentDetails = sinon.spy();
const wrapper = shallow(
<MyComponent fetchPaymentDetails={fetchPaymentDetails} />
);
wrapper.find('button').simulate('click');
expect(props.fetchPaymentDetails).to.have.property('callCount', 1);
});