You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel AssertableJson仅测试响应的data属性

解决Laravel中使用AssertableJson仅测试响应data属性的问题

你之前的写法错误在于直接调用$response->data,Response实例并没有这个属性,正确的做法是通过assertJson闭包来定位到data节点,以下是几种可行的实现方式:

方式一:直接指定data下的字段路径

在断言时给字段加上data.前缀,直接定位到用户对象的属性:

$response->assertJson(function (AssertableJson $json) {
    $json->whereType('data.id', 'string')
         ->where('data.email', 'email@gmail.com')
         // 其他断言规则
         ->etc();
});

方式二:使用within方法限定断言范围

通过within方法将断言上下文限定在data节点内部,这样后续的断言无需重复写data.前缀:

$response->assertJson(function (AssertableJson $json) {
    $json->within('data', function (AssertableJson $data) {
        $data->whereType('id', 'string')
             ->where('email', 'email@gmail.com')
             // 其他断言规则
             ->etc();
    });
});

方式三:使用箭头函数简化写法

如果喜欢更简洁的语法,可以用箭头函数嵌套实现:

$response->assertJson(fn (AssertableJson $json) => 
    $json->has('data', fn (AssertableJson $data) => 
        $data->whereType('id', 'string')
             ->where('email', 'email@gmail.com')
             // 其他断言规则
             ->etc()
    )
);

以上三种方式都可以精准针对响应中的data属性(用户对象)进行断言,忽略meta部分的内容。

内容的提问来源于stack exchange,提问作者Melly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:25:29