'How to get the response data in laravel unit testing
I have been trying to work with laravel unit testing. What I wanted was how to get the response data of original.
public function testProducts()
{
$response=$this->call('GET','/products',['cat','all']);
// dd($response);
$data = $response->getData();
// dd($data);
}
When I dd in the first case it shows me HTML content. What I want to be shown is the real content with array. What should I do ?
Solution 1:[1]
You do not need to get the data out. Instead use assertJson()
. You simply build your JSON
structure as a PHP
associate array and it will assert it by JSON
encoding it.
$response->assertJson([
[
'name' => 'Iphone',
]
]);
Solution 2:[2]
Create different product first on the same test case and then check with assertJSon
factory(product::class)->create(['name' => 'Cat']);
factory(product::class)->create(['name' => 'all']);
factory(product::class)->create(['name' => 'other']);
$response = $this->json('GET', '/api/products', ['Cat','all'])
->assertStatus(200)
->assertJson([
[ 'name' => 'cat'],['name'=>'all']
]);
Solution 3:[3]
$response->viewData() may be the method you're looking for.
If, for example, you do a dd($response) and see that you have an instance of an object "model", and that object has a field "column", you'd do:
$val = $response->viewData("model")->column;
to get the value of that property.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mrhn |
Solution 2 | mrhn |
Solution 3 | iateadonut |