使用Jest测试React Context时如何在测试文件中消费Context
要测试这个Currency Context,你需要将消费逻辑包裹在CurrencyContextProvider中运行,常用两种测试方案如下:
方案1:模拟真实组件消费场景(更贴近实际使用)
你可以写一个简易的测试用消费组件,通过组件的行为验证Context的功能是否正常,完整测试代码如下:
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import CurrencyContextProvider, { CurrencyContext } from "../contexts/CurrencyContext"; // 测试用消费组件,仅用于读取和触发Context能力 const TestConsumer = () => { const { selectedCurrency, setCurrency } = React.useContext(CurrencyContext); return ( <div> <span data-testid="currency">{selectedCurrency}</span> <button onClick={() => setCurrency('CNY')} data-testid="change-btn">切换货币</button> </div> ) } test("Currency Context初始值与更新功能正常", () => { // 用Context Provider包裹测试组件 render( <CurrencyContextProvider> <TestConsumer /> </CurrencyContextProvider> ) // 验证初始默认货币为USD expect(screen.getByTestId('currency')).toHaveTextContent('USD') // 触发Context的setCurrency方法 userEvent.click(screen.getByTestId('change-btn')) // 验证货币值已更新为CNY expect(screen.getByTestId('currency')).toHaveTextContent('CNY') })
方案2:轻量化测试Context核心逻辑(无需额外写测试组件)
如果你只需要验证Context本身的状态和方法逻辑,不需要模拟组件交互,可以用renderHook直接测试Context的消费结果:
import React from 'react'; import { renderHook, act } from '@testing-library/react'; import CurrencyContextProvider, { CurrencyContext } from "../contexts/CurrencyContext"; test("Currency Context初始值与更新功能正常", () => { // 配置Provider作为wrapper,直接调用useContext获取Context值 const { result } = renderHook(() => React.useContext(CurrencyContext), { wrapper: CurrencyContextProvider }) // 验证初始值 expect(result.current.selectedCurrency).toBe('USD') // 调用更新方法,需要包裹在act中保证状态更新完成后再断言 act(() => { result.current.setCurrency('EUR') }) // 验证更新结果 expect(result.current.selectedCurrency).toBe('EUR') })
如果你的项目中还没有安装@testing-library/react和@testing-library/user-event,安装对应版本即可运行上述测试用例。
内容的提问来源于stack exchange,提问作者asem shaat
相关产品推荐
相关产品推荐

