简体   繁体   English

如何使用Jest在ES6类方法中测试对redux存储的调度?

[英]How can I test a dispatch to a redux store in an ES6 class method with Jest?

I try to test that a dispatch to a redux store is happening inside an ES6 class method, but I'm failing miserably. 我尝试测试是否在ES6类方法内发生了对redux存储的调度,但是我失败了。

Somehow I'm unable to find out how to mock the store to get a response. 我以某种方式无法找到如何模拟商店以获取响应的方法。

The method is quite simple: 方法很简单:

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

I just want to test that the dispatch happened. 我只想测试调度是否已发生。

I tried a couple of things, including redux-mock-store , but I get no feedback from the store. 我尝试了一些操作,包括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: [] }
});

I would be deeply grateful if someone could point me in the right direction. 如果有人能指出正确的方向,我将深表感谢。

The jest store mock isn't invoked because the class doesn't have access to it. 不能调用Jest store模拟,因为该类无权访问它。 One way around this would be passing in the store to the constructor: 解决此问题的一种方法是将存储传递给构造函数:

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM