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

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

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 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