Reputation: 13
I have a laravel 8 Unit Test which looks like this:
public function testAddingTwoCars()
{
$response = $this->postJson('api/basket', ['cars' => [['name' => 'car one'], ['name' => 'car two']]]);
$response
->assertStatus(200)
->assertJson(['total' => 40]);
}
In my route I have:
Route::post('/api/basket',[basketController::class, 'store']);
In my controller I have:
public function store(Request $request)
{
$data = $request->all();
return response()->json($data);
}
when I run the test with php artisan test
it shows this:
• Tests\Unit\BasketTest > adding two cars
Unable to find JSON:
[{
"total": 40
}]
within response JSON:
[{
"cars": [
{
"name": "car one"
},
{
"name": "car two"
}
]
}].
How do I:grab the total as its not in $request
so that I could do something like this in my controller:
$public function store(Request $request)
{
$data = $request->all();
$data['total'] = 40;
return response()->json($data);
}
The above works, but it is hard coded so is not the best way to do it
Upvotes: 0
Views: 5097
Reputation: 76639
->assertJson(['total' => 40])
is non-sense; this will not pass unless the JSON has it:
return response()->json(['data' => $data, 'total' => 40]);
Upvotes: 0
Reputation: 1384
assertJson
Assert that the response contains the given JSON data:
$response->assertJson(array $data, $strict = false);
The assertJson
method converts the response to an array and utilizes PHPUnit::assertArraySubset
to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.
You can read about it at this link
https://laravel.com/docs/8.x/http-tests#assert-json
and Here
https://laravel.com/docs/5.4/http-tests#testing-json-apis
and you can check this video too
https://adamwathan.me/2016/11/16/the-only-json-assertion-youll-ever-need/
Upvotes: 1