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

175
Visualizações
How to test that a function prop was called in react-testing-library

There are 3 files:

File 1: helpers.js

export const helpers = () => ({
  bar: () => 'Bar was called',
});

File 2: TestComponent.js

import React from 'react';
import { helpers } from './helpers';

const TestComponent = () => {
  const { bar } = helpers();
  return (
    <><button onClick={bar}/></>
  );
};

export default TestComponent;

File 3: TestComponent.test.js

import React from 'react';
import userEvent from '@testing-library/user-event';
import { screen, render } from '@testing-library/react';
import TestComponent from './TestComponent';
import { helpers } from './helpers';

jest.mock('./helpers', () => ({
  helpers: jest.fn(),
}));

test('bar is called', () => {
  helpers.mockImplementation(() => ({
    bar: jest.fn(),
  }));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(???????).toHaveBeenCalled();
});

This line is the key:

expect(???????).toHaveBeenCalled();

The question: How can I test if bar function was called? I was expecting that something similar to expect(helpers().bar) would work. But it doesn't.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

save the function in a variable and use it in expect

test('bar is called', () => {
  const bar = jest.fn()
  helpers.mockImplementation(() => ({bar}));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(bar).toHaveBeenCalled();
});
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