Ad

React - Redux: Testing Actions Dispatched Inside Other Actions

- 1 answer

I'm using redux for a react app, with a thunk middleware.

I have this method:

export function login(username, password) {
    return function (dispatch, getState) {
        dispatch(loginRequest());
        return sessionService.login(dispatch, username, password).then(redirectTo => {
            dispatch(handleSuccessfulAuthentication(redirectTo));
        }).catch(error => {...}
    };
}

So I'm nocking the result of the service, and get the actions ok. But I want to test I'm dispatching the method handleSuccessfulAuthentication but spying on that method does not seems to work, it always return it was not called (besides I see the action returned)

This is basically my test:

describe('WHEN logging in from sessionExpired', () => {
    let action;
    beforeAll(() => {
        ...
        testHelper.getUnAuthenticatedNock()
          .post(`/${endpoints.LOGIN}`, credentials)
          .reply(200, {
              ...loginResponse
          });
        action = sinon.spy(sessionActions, 'handleSuccessfulAuthentication');
        return store.dispatch(sessionActions.login(credentials.username, credentials.password))
    }
    it('Should redirect to previous visited page', () => {
        console.log(action.called); // false
    });
Ad

Answer

You need to call the exported function (please note we're calling handleSuccessfulAuthentication bound to exports):

export function login(username, password) {
    return function (dispatch, getState) {
        dispatch(loginRequest());
        return sessionService.login(dispatch, username, password).then(redirectTo => {
            dispatch(exports.handleSuccessfulAuthentication(redirectTo));
        }).catch(error => {...}
    };
}

And then your test:

it('Should redirect to previous visited page', () => {
    console.log(action.called); // false
});

It's a weird issue where you have to call the function bound to exports. More information found here: https://github.com/facebook/jest/issues/936#issuecomment-214939935

Ad
source: stackoverflow.com
Ad