如何测试数组在AssertableJson在Laravel 8?



在我的Laravel项目中,我想测试一个JSON响应,它实际上是一个带有data键的分页器结果。它是一个数组,它包含一些元素。我们不知道确切的数量,因为它来自于一个函数。

我的问题是,如果分页限制是10,并且我更改了超过分页限制的元素数量,例如20,我仍然只得到10个元素。但是我也想测试一下。

现在我有了这样的代码:

$response
->assertSuccessful()
->assertJson(function (AssertableJson $json) use ($allElementsCount) {
$json
->has('data')
->whereType('data', 'array')
// here I want to test the count of 'data' array
->etc();
});

如何在JSON响应中测试数组计数?

可以使用

$response->assertJsonCount(10, 'data');

参考

我通常使用

$reponse->assertJson(fn (AssertableJson $json) => $json
->has('data', 10); // expect data has 10 items
->count('data', 10) // this also works, but I don't use this for no reason
// and while at it, this is my way to make sure the order is correct
->where('data.0.id', $items[0]->id)
->where('data.1.id', $items[1]->id)
);

如果只需要一个项目

$reponse->assertJson(fn (AssertableJson $json) => $json
// expect data has 1 item, and has these attributes
->has('data', 1, fn (AssertableJson $json) => $json
->where('id', $item->id)
->where('name', $item->name)
)
);

相关内容

  • 没有找到相关文章

最新更新