【问题标题】:ngrx action: how to test that action is dispatchedngrx 动作:如何测试该动作已被调度
【发布时间】:2021-08-20 21:42:46
【问题描述】:

如何对一个动作是否被调度进行单元测试?

例如我有这个简单的方法

 public openInfo()
  {
    this.store.dispatch(InfoActions.openInfo({
      Configuration: {
        message: 'This is an info message!'
      }
    }));
  }

我需要编写一个单元测试来验证操作是否已分派:

   it('should dispatch openInfo action', function () {

    // how to check the dispactched actions and their parameters?
    // expect(...)
  });

如何检查已分派的操作?

【问题讨论】:

    标签: angular unit-testing jestjs


    【解决方案1】:

    您不必这样做。您需要在商店中使用间谍。

    在 store.dispatch 上创建一个间谍并使用

    expect(store.dispatch).toHaveBeenCalledWith(...)
    

    你就完成了。调度的实际测试属于store单元测试。

    【讨论】:

      【解决方案2】:

      首先在派发之前监视商店:

      const spyDispatch = spyOn(store, 'dispatch');
      

      之后,您可以期待一个复杂的动作(很难重新创建):

      const myActionType = InfoActions.openInfo.type;
      expect(spyDispatch).toHaveBeenCalledWith(jasmine.objectContaining({ type: myActionType  }));
      

      您可以在此处找到有关jasmine.objectContaining 的更多信息:

      https://jasmine.github.io/2.0/introduction#section-Partial_Matching_with_%3Ccode%3Ejasmine.objectContaining%3C/code%3E

      【讨论】:

        猜你喜欢
        • 2018-12-07
        • 2020-01-25
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2018-01-04
        • 1970-01-01
        相关资源
        最近更新 更多