如何在TypeScript环境用React Testing Library测试接收setState的子组件
你可以根据测试需求选择以下任意一种方式传入符合类型要求的setResult属性,通过TypeScript检查:
- 仅需满足类型校验,不需要验证
setResult的调用逻辑:直接传入空箭头函数即可,类型会自动匹配:
test('render component correctly', () => { render(<TestChild setResult={() => {}}/>) // 其余测试逻辑 })
- 需要在测试中验证
setResult的调用次数、传入参数是否符合预期:可以传入jest模拟函数,可通过类型标注或者类型断言匹配类型:
import type { Dispatch, SetStateAction } from 'react' import type { IResult } from '你的类型定义文件路径' test('should trigger setResult with correct value', () => { // 写法1:类型断言,写法更简洁 const mockSetResult = jest.fn() as Dispatch<SetStateAction<IResult | null>> // 写法2:给jest.fn标注泛型,类型约束更严格 // const mockSetResult = jest.fn<ReturnType<Dispatch<SetStateAction<IResult | null>>>, Parameters<Dispatch<SetStateAction<IResult | null>>>>() render(<TestChild setResult={mockSetResult}/>) // 触发子组件中调用setResult的操作逻辑后,验证调用结果 expect(mockSetResult).toHaveBeenCalledWith(/* 你预期的参数 */) })
如果有多个测试用例都需要传入setResult,可以把mock函数抽成公共复用逻辑,避免每个用例重复声明。
内容的提问来源于stack exchange,提问作者Moon
相关产品推荐
相关产品推荐

