如何在Inertia单元测试中校验响应包含指定字符串?
Inertia测试断言嵌套节点包含指定字符串方案
直接使用AssertableInertia提供的where方法配合自定义闭包即可实现校验,不需要依赖常规HTTP测试的assertSee(),whereContains()仅支持节点值全等匹配,无法覆盖数组包含、子字段模糊匹配的场景。
调试完成后先移除链式调用里的dd('profile.0.buttons'),再根据你的buttons节点结构选对应断言写法:
1. buttons为字符串数组/集合的场景
如果profile.0.buttons是直接存储字符串的列表(比如['编辑', '删除', '导出']),要校验列表内存在目标字符串,写法如下:
->assertInertia( fn (AssertableInertia $page) => $page ->component('UsersPage') ->has('profile') ->has('profile.0.buttons') ->where('profile.0.buttons', function ($buttons) { return in_array('替换为你要校验的目标字符串', $buttons); }, 'profile.0.buttons节点中不存在目标字符串') );
2. buttons为结构化数组的场景
如果profile.0.buttons是结构化列表(每个元素为带字段的数组/对象,比如包含label、action字段的按钮配置),要校验某个子项的字段包含目标字符串,写法如下:
->assertInertia( fn (AssertableInertia $page) => $page ->component('UsersPage') ->has('profile') ->has('profile.0.buttons') ->where('profile.0.buttons', function ($buttons) { foreach ($buttons as $button) { // 按需替换判断逻辑,str_contains可实现字符串模糊匹配 if (str_contains($button['label'], '替换为你要匹配的字符串片段')) { return true; } } return false; }, '按钮列表中未找到匹配目标字符串的项') );
注意事项
- 断言前保留
has('profile.0.buttons')调用,避免节点不存在时闭包接收到null引发报错 - 闭包返回
true即代表断言通过,返回false时会抛出第三个参数传入的自定义错误提示 - 字符串模糊匹配优先使用Laravel内置的
str_contains()辅助函数,无需手动实现字符串查找逻辑
内容的提问来源于stack exchange,提问作者jkstallard
相关产品推荐
相关产品推荐

