Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
Testing mapDispatchToProps calls have fired with ReactTestingLibrary

I am using mapDispatchToProps to make a dispatch call to an API in the useEffect of my functional component.

I am a little stuck as how to actually test this in my unit tests with React Testing Library.

I can pass my Redux store quite easily, however I don't think I've ever had to pass the dispatch before and I'm a little lost.

I did try to pass the dispatch function with my store, but this of course didn't work.

Component

const mapDispatchToProps = dispatch => ({
    myDispatchFunction: () => dispatch(someDispatch())
});
const mapStateToProps = ({someStateProp}) => ({
    myStateProp: !!someStateProp // This isn't important
});

const MyComp = ({myDispatchFunction}) => {
    useEffect(() => {
        !!myStateProp && myDispatchFunction();
    }, []);

    return ...
}

Test

it('Should trigger dispatch function on load', () => {
    const mockFunc = jest.fn(); // My attempt at mocking the dispatch call
    const store = {someStateProp: true, myDispatchFunction: mockFunc};
    render(
        <Provider store={mockStore(store)}>
            <MyComponent />
        </Provider>
    );

    expect(mockFunc).toHaveBeenCalled();
});

This fails...

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code has no real meaning, but the same with the test method, try not to mock functions and modules that have no side effects, I/O operations, and use their original implementation.

For your example, don't mock mapStateToProps, mapDispatchToProps, and dispatch functions. We can create a test store, populate the test state data, and collect the dispatch actions in the component.

If your component uses some state slice, verify that your component is rendering correctly. This is also called behavior testing. This testing strategy is more robust if the component behaves correctly, regardless of whether your implementation changes.

Why not mock? Like mapStateToProps, where a mock implementation changes its behavior if you don't know how it is implemented, resulting in an error-based implementation of the test case. Your tests may pass but the actual code at runtime is not correct.

E.g.

index.tsx:

import { useEffect } from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = (dispatch) => ({
  myDispatchFunction: () => dispatch({ type: 'SOME_ACTION' }),
});
const mapStateToProps = ({ someStateProp }) => ({
  myStateProp: !!someStateProp,
});

const MyComp = ({ myDispatchFunction, myStateProp }) => {
  useEffect(() => {
    !!myStateProp && myDispatchFunction();
  }, []);

  return null;
};

export default connect(mapStateToProps, mapDispatchToProps)(MyComp);

index.test.tsx:

import { render } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import MyComp from './';

describe('71555438', () => {
  test('should pass', () => {
    let dispatchedActions: any[] = [];
    const store = createStore(function rootReducer(state = { someStateProp: 'fake value' }, action) {
      if (!action.type.startsWith('@@redux')) {
        dispatchedActions.push(action);
      }
      return state;
    });
    render(
      <Provider store={store}>
        <MyComp />
      </Provider>
    );
    expect(dispatchedActions).toEqual([{ type: 'SOME_ACTION' }]);
  });
});

Test result:

 PASS  stackoverflow/71555438/index.test.tsx (9.562 s)
  71555438
    ✓ should pass (16 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.565 s

Note: We should ignore the action dispatched by createStore internally and we only need to collect the actions dispatched by users(our code).

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!