【问题标题】:Sinon & React - check if mapToDispatch methods are calledSinon & React - 检查是否调用了 mapToDispatch 方法
【发布时间】:2017-06-06 21:46:05
【问题描述】:

如果您有 mapDispatchToProps 并且您想检查这些方法是否在您的组件实例方法之一中被调用。所以:

const mapDispatchToProps = (dispatch) => {
  return {
    fetchPaymentDetails: () => dispatch(fetchPaymentDetails()),
    updatePaymentDetails: (payload) => dispatch(updatePaymentDetails(payload)),
    clearServerErrors: () => dispatch(clearServerErrors())
  }
}

然后在组件内的一个方法中:

 submit(e) {
    this.props.clearServerErrors();
 }

所以我们可以触发submit 函数,但是我们想知道this.props.clearServerErrors 确实被调用了。

到目前为止,我已经尝试了很多方法来测试这个涉及到 sinon spys 和 stubs 的方法,但我无法验证 props 方法是否真的被调用了。

在我看来,我在挂载时传入的方法间谍被 mapDispatchToProps 覆盖

关于如何检查 mapDispatchToProps 中的 prop 方法是否被调用有什么建议吗?

【问题讨论】:

    标签: reactjs sinon


    【解决方案1】:

    你真的要求测试两个不同的东西:

    1. mapToProps 会像您怀疑的那样调用您的操作助手
    2. 当触发事件时,将调用作为 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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-02
      • 2019-06-06
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 2017-04-02
      相关资源
      最近更新 更多