Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda