【问题标题】:How can I test a dispatch to a redux store in an ES6 class method with Jest?如何使用 Jest 在 ES6 类方法中测试对 redux 存储的调度?
【发布时间】:2019-07-29 18:22:18
【问题描述】:

我尝试测试在 ES6 类方法内发生对 redux 存储的调度,但我失败了。

不知何故,我不知道如何模拟商店以获得响应。

方法很简单:

class Foo {
  …
  bar() {
    store.dispatch({ type: FOO_BAR_BAZ });
  }
  …
};

我只是想测试一下调度是否发生了。

我尝试了几件事,包括redux-mock-store,但我没有从商店得到任何反馈。

it('should foo bar baz', () => {
  const store = {
    dispatch: jest.fn(),
  };

  const foobar = new Foo();
  foobar.bar();

  console.log(store.dispatch.mock);
  //=> { calls: [], instances: [], invocationCallOrder: [], results: [] }
});

如果有人能指出正确的方向,我将不胜感激。

【问题讨论】:

    标签: javascript unit-testing ecmascript-6 jestjs es6-class


    【解决方案1】:

    开玩笑的store 模拟未被调用,因为该类无权访问它。解决这个问题的一种方法是将存储传递给构造函数:

    class Foo {
      constructor(store) {
        this.store = store
      }
    
      bar() {
        this.store.dispatch({ type: FOO_BAR_BAZ });
      }
    }
    

    -

    it('should foo bar baz', () => {
      const store = {
        dispatch: jest.fn(),
      };
    
      const foobar = new Foo(store);
      foobar.bar();
    
      console.log(store.dispatch.mock);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 2018-01-04
      • 2018-09-14
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      相关资源
      最近更新 更多