Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda