简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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