测试与构建 React 组件的高级技巧
1. 构建组件模拟的匹配器
在测试组件时,我们常常需要验证组件是否以特定的属性进行渲染。为了简化这个过程,我们可以构建自定义的匹配器。
1.1 匹配器概述
我们将介绍两个匹配器: toBeRenderedWithProps 和 toBeFirstRenderedWithProps 。 toBeRenderedWithProps 用于验证组件当前是否以给定的属性进行渲染,它等价于使用 toHaveBeenLastCalledWith 匹配器。 toBeFirstRenderedWithProps 则用于检查子组件属性的初始值,在任何 useEffect 钩子运行之前。
1.2 toBeRenderedWithProps 匹配器的实现步骤
以下是实现 toBeRenderedWithProps 匹配器的详细步骤:
1. 创建测试文件 :在 test/matchers/toBeRenderedWithProps.test.js 中创建新的匹配器测试文件,并添加以下导入:
import React from "react";
import {
toBeRenderedWithProps,
}
超级会员免费看
订阅专栏 解锁全文
921

被折叠的 条评论
为什么被折叠?



