Home Redux - Jest: Testing functions that have void return
Reply: 1

Redux - Jest: Testing functions that have void return

Exuro
1#
Exuro Published in 2017-07-17 22:57:03Z

New to Jest and Redux and I'm having trouble with testing functions that are dispatching to the store but don't yield a return value. I'm trying to follow the example from the Redux website does this

return store.dispatch(actions.fetchTodos()).then(() => {
      // return of async actions
      expect(store.getActions()).toEqual(expectedActions)
})

however I have several "fetchtodos" functions that don't return anything which causes the error "TypeError: Cannot read property 'then' of undefined" due to returning undefined. I'm wondering what I can do to test that my mock store is correctly updating. Is there a way to dispatch the function, wait for it to finish and then compare the mock store with expected results?

Thanks

edit: We're using typescript

action from tsx

export function selectTopic(topic: Topic | undefined): (dispatch: Redux.Dispatch<TopicState>) => void {
  return (dispatch: Redux.Dispatch<TopicState>): void => {

    dispatch({
      type: SELECT_Topic,
      payload: topic,
    });

    dispatch(reset(topic));
  };
}

test.tsx

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('Select Topic action', () => {
  it('should create an action to select .', () => {
    const topic: Topic = mockdata.example[0];
    const expectedAction = {
      type: actions.SELECT_TOPIC,
      payload: topic,
    };

    const store = mockStore(mockdata.defaultState);

    return store.dispatch(actions.selectTopic(topic)).then(() => {
      expect(store.getState()).toEqual(expectedAction);
    });
  });
});

The action is what I'm given to test(and there are many other functions similar to it. I'm getting that undefined error when running the test code, as the function isn't returning anything.

Danny Delott
2#
Danny Delott Reply to 2017-07-17 23:03:29Z

In Redux, the store's dispatch method is synchronous unless you attach middleware that changes that behavior, ie: returns a promise.

So this is likely a redux configuration problem. Be sure you are setting up your test store with the same middleware that allows you to use the promise pattern in production.

And as always, be sure to mock any network requests to avoid making api calls in test.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309772 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO