Search code examples
reactjsreduxjestjsenzymeredux-thunk

How can I test history.push inside action?


How can I test history.push inside action?

export const startLogout = () => {
return ( dispatch ) => {

    return firebase
        .auth()
        .signOut()
        .then(() => {
            dispatch( logout() );
            history.push( '/login' );
        })
        .catch( ( err ) => {
            // Simple redirect to non existent route
            history.push( '/oops' );
            console.log( err );
        });
};

};

test( 'should start logout', ( done ) => {
const store = createMockStore({});

store.dispatch( startLogout() ).then(() => {
    const actions = store.getActions();

    expect( actions[0] ).toEqual({
        type: LOGOUT
    });

    const history = { push: jest.fn() };
    expect( history.push ).toHaveBeenLastCalledWith( '/login' );

    done();
}).catch((err) => {
    console.log( err );
    done();
});

});

This current code gives me this error:

Expected mock function to have been last called with: ["/login"] But it was not called.

Thank you


Solution

  • You are creating a local history object and setting its push property to a spy right before you test to see if that local history.push spy was called.

    You need to create the spy on the history.push used in startLogout, and it needs to be in place before you dispatch the startLogout action.