'How can I check if signOut was called in this test with Jest?

I am trying to test my home page in a next app, but I have a button in Home that call a log out firebase function. I've tried to mock this function and check if was called, but no success. How can I do it correctly?

import { fireEvent, render, screen } from '@testing-library/react';

import Home from '../../pages/index';

jest.mock('firebase/app', () => {
  return {
    auth: () => {
      return {
        signOut: () => jest.fn(),
      };
    },
  };
});

describe('Page: Home', () => {
  it('render the page correctly', () => {
    render(<Home />);
  });

  it('Sign out if signOut button is clicked', () => {
    render(<Home />);

    const logOutButton = screen.getByText('Sair');

    fireEvent.click(logOutButton);

    // TODO: Check if signOut was called

    // expect().toHaveBeenCalled();
  });
});


Solution 1:[1]

Try this and see if it works:

import { fireEvent, render, screen } from '@testing-library/react';

import Home from '../../pages/index';

const signOutSpy = jest.fn()

jest.mock('firebase/app', () => {
  return {
    auth: () => {
      return {
        signOut: signOutSpy,
      };
    },
  };
});

describe('Page: Home', () => {
  it('render the page correctly', () => {
    render(<Home />);
  });

  it('Sign out if signOut button is clicked', () => {
    render(<Home />);

    const logOutButton = screen.getByText('Sair');

    fireEvent.click(logOutButton);

    expect(signOutSpy).toHaveBeenCalled();
  });
});

(just remember to reset/clear all mocks between the tests)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Norfeldt