Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Mocking Functions and Modules | Advanced Testing and Test Maintenance
Testing React Apps with Jest and React Testing Library

bookMocking Functions and Modules

When testing React components, you often want to focus on the logic inside your component without being affected by the behavior of external dependencies. This is where mocking comes in. Mocking is the process of replacing real functions, modules, or API calls with controlled mock implementations during testing. You should mock dependencies when your component interacts with complex logic outside its scope, such as utility functions, third-party libraries, or network requests. By mocking these, you can isolate your component's behavior, make your tests faster, and ensure they are reliable and repeatable. For example, if your component calls an API to fetch data, you should mock the API call so your test does not depend on network availability or external data changes.

Suppose you have a utility module called api.js that exports a fetchData function. Your component uses this function to load data. In your test, you can use jest.mock to replace the real fetchData with a mock version that returns predictable data. This allows you to verify that your component behaves correctly based on the mocked data, and to check how many times the function was called or with which arguments.

Here is how you might mock a module and test its usage:

api.js

export const fetchData = () => {
  // Real implementation makes a network request
};

MyComponent.jsx

import { fetchData } from "./api";
import { useEffect, useState } from "react";

export function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchData().then(result => setData(result));
  }, []);

  return <div>{data ? data : "Loading..."}</div>;
}

MyComponent.test.js

// MyComponent.test.js
import { render, screen } from "@testing-library/react";
import { MyComponent } from "./MyComponent";
import * as api from "./api";

jest.mock("./api");

test("displays data returned by fetchData", async () => {
  api.fetchData.mockResolvedValue("Mocked Data");

  render(<MyComponent />);

  const resolvedElement = await screen.findByText("Mocked Data");
  expect(resolvedElement).toBeInTheDocument();
  expect(api.fetchData).toHaveBeenCalledTimes(1);
});

In this example, the real fetchData function is replaced with a mock that returns "Mocked Data". The test checks that the component renders the mocked data and verifies that the mock function was called exactly once.

Note
Study More

Find detailed explanations and advanced use cases in the official Jest documentation on mocking.

question mark

What is the main purpose of mocking in testing React components?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Suggested prompts:

Can you explain how to mock other types of dependencies, like third-party libraries?

What are some best practices for mocking in React tests?

How do I reset or clear mocks between tests?

bookMocking Functions and Modules

Stryg for at vise menuen

When testing React components, you often want to focus on the logic inside your component without being affected by the behavior of external dependencies. This is where mocking comes in. Mocking is the process of replacing real functions, modules, or API calls with controlled mock implementations during testing. You should mock dependencies when your component interacts with complex logic outside its scope, such as utility functions, third-party libraries, or network requests. By mocking these, you can isolate your component's behavior, make your tests faster, and ensure they are reliable and repeatable. For example, if your component calls an API to fetch data, you should mock the API call so your test does not depend on network availability or external data changes.

Suppose you have a utility module called api.js that exports a fetchData function. Your component uses this function to load data. In your test, you can use jest.mock to replace the real fetchData with a mock version that returns predictable data. This allows you to verify that your component behaves correctly based on the mocked data, and to check how many times the function was called or with which arguments.

Here is how you might mock a module and test its usage:

api.js

export const fetchData = () => {
  // Real implementation makes a network request
};

MyComponent.jsx

import { fetchData } from "./api";
import { useEffect, useState } from "react";

export function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchData().then(result => setData(result));
  }, []);

  return <div>{data ? data : "Loading..."}</div>;
}

MyComponent.test.js

// MyComponent.test.js
import { render, screen } from "@testing-library/react";
import { MyComponent } from "./MyComponent";
import * as api from "./api";

jest.mock("./api");

test("displays data returned by fetchData", async () => {
  api.fetchData.mockResolvedValue("Mocked Data");

  render(<MyComponent />);

  const resolvedElement = await screen.findByText("Mocked Data");
  expect(resolvedElement).toBeInTheDocument();
  expect(api.fetchData).toHaveBeenCalledTimes(1);
});

In this example, the real fetchData function is replaced with a mock that returns "Mocked Data". The test checks that the component renders the mocked data and verifies that the mock function was called exactly once.

Note
Study More

Find detailed explanations and advanced use cases in the official Jest documentation on mocking.

question mark

What is the main purpose of mocking in testing React components?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 1
some-alt