arctic
arctic

Reputation: 819

How to test if a functions is called in React?

Working template of the project: https://codesandbox.io/s/blue-currying-3me1t

The only test I have set up is in src/App.test.js to check that a name is rendered. I am trying to setup another test that checks to see if a function is called before the buttons are generated.

In FontAwesome.js there is a registerIcons() function that registers all of the icons needed for the website. I call this function in Buttons.js as it is the place where I use the icons.

I want to create a test in App.test.js that checks to see if registerIcons() is called before the buttons are created in Buttons.js.

Upvotes: 2

Views: 2066

Answers (1)

CampbellMG
CampbellMG

Reputation: 2220

You could typically do this by manually mocking your FontAwesome dependency like this:

import React from "react";
import { render } from "@testing-library/react";
import Button from "./Buttons.js";
import registerIcons from './FontAwesome'

jest.mock('./FontAwesome', () => ({
  __esModule: true
  default: jest.fn()
}))


test("registers icons", () => {
  render(<Button />);

  expect(registerIcons).toHaveBeenCalled();
});

However, it seems code sandbox does not currently support mocking. You could try it in your own IDE though.

Upvotes: 2

Related Questions