我有一个组件,它使用useContext,然后它的输出取决于上下文中的值。一个简单的例子:
useContext
import React, { useContext } from 'react'; const MyComponent = () => { const name = useContext(NameContext); return <div>{name}</div>; };
当使用来自 react 和 jest 快照的浅渲染器测试此组件时。我该如何更改 的值NameContext?
NameContext
useContext当测试使用
MyComponent以下是测试com的示例
MyComponent
和复制代码import React, { useContext } from 'react'; import { render } from '@testing-library/react'; import MyComponent from './MyComponent'; // Mock context value const mockContextValue = 'John Doe'; // Mock context object const mockContext = { Consumer: ({ children }) => children(mockContextValue), }; // Mock useContext hook jest.mock('react', () => ({ ...jest.requireActual( ...je 'react'), useContext: jest.fn().mockImplementation(() => mockContextValue), })); describe('MyComponent', () => { it('should render with the correct context value', () => { const { container } = render( <mockContext.Provider value={mockContext}> <MyComp <mockContext.Provider value={mockContext}> <MyComponent /> </mockContext.Provider> ); ); e expect(container.textContent).toBe(mockContextValue); }); });
在此示例中:
mockContextValue
MyComponent``NameContext
mockContext
Consumer
mockContext.Provider
这种方法允许你在测试期间控制上下文值,并确保你的组件表现良好