Search code examples
reactjsreduxreact-reduxjestjsreact-tsx

Spy on redux dispatch method


I am a newbie with jest and I am writing unit tests to my react application, which is using redux and which is written with Typescript.

I have my container component with this piece of code:

const mapDispatchToProps = (dispatch: Dispatch<any>) => ({
    onSelectScenario: (selectedScenario: any) => {
        dispatch(selectScenario(selectedScenario));
    }
});

I want to write a unit test checking that when I call this prop from the test (onSelectScenario), the dispatch method will be called with the right params.

Any idea how to spy on this dispatch?

This is my unit test where I call the prop method:

it('should dispatch', () => {
    component.props().onSelectScenario('New Selected Scenario');
});

And this is the setup of the tests where I define my container component providing the mocked store:

const mockStore = configureMockStore();
let store = mockStore({
    scenarios: ['Scenario 1', 'Scenario 2']
});
let component: ShallowWrapper<any, any>;

describe('ScenarioListGroupContainer Component', () => {
    beforeEach(() => {
        component = shallow(<ScenarioListGroupContainer store={store} />);
    });
    // ...
});

Solution

  • The best solution I've found so far (any better suggestion is more than welcome) is the following, keeping exactly the same code provided in my question:

    it('should dispatch the select scenario action', () => {
        component.props().onSelectScenario('New Selected Scenario');
        expect(store.getActions()).toEqual([{ 
            type: 'SELECT_SCENARIO', 
            selectedScenario: 'New Selected Scenario' 
        }]);
    });
    

    So you manually call your prop and then you check if the action has been dispatched correctly in the store