fjplaurr
fjplaurr

Reputation: 1950

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.

Upvotes: 1

Views: 4429

Answers (1)

scr2em
scr2em

Reputation: 1024

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();
});

Upvotes: 2

Related Questions