乐闻世界logo
搜索文章和话题

How to mock react context in Jest

1个答案

1

When using Jest to test React applications, sometimes we need to mock the entire React Context to test components in isolation, free from external data influences. Below, I'll explain how to use Jest to mock React Context.

Step 1: Create Your React Context

Suppose we have a React Context like this:

javascript
import React, { createContext, useContext } from 'react'; const MyContext = createContext(); export const useMyContext = () => useContext(MyContext); export const MyProvider = ({ children }) => { const value = { someData: 'original data' }; return ( <MyContext.Provider value={value}> {children} </MyContext.Provider> ); };

Here, MyProvider serves as a Context Provider, supplying data to child components.

Step 2: Mock React Context in Jest

When testing, if you need to mock this Context to control the data passed to components, proceed as follows:

  1. Create a test file, such as MyComponent.test.js.
  2. Import necessary modules, including React, the component to test, and the hooks to mock, etc.
  3. Use jest.mock() to intercept the useContext hook.

For example:

javascript
import React from 'react'; import { render, screen } from '@testing-library/react'; import { useMyContext } from './MyContext'; // Import our custom hook import MyComponent from './MyComponent'; jest.mock('./MyContext', () => ({ useMyContext: jest.fn(), })); describe('MyComponent', () => { it('should display mock data from context', () => { // Set the mocked value returned by `useMyContext` useMyContext.mockReturnValue({ someData: 'mocked data' }); // Render the component render(<MyComponent />); // Verify the component renders the mocked data expect(screen.getByText(/mocked data/i)).toBeInTheDocument(); }); });

In this example, jest.mock() intercepts the ./MyContext module import, providing a custom implementation where useMyContext returns a mocked value. Thus, when MyComponent calls useMyContext(), it receives the mocked value specified in the test.

Summary

This approach enables controlling Context values without altering component code, making it ideal for testing components reliant on external data. By mocking the React Context, you can supply any desired test scenarios, ensuring components function correctly across various states.

2024年6月29日 12:07 回复

你的答案