Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel/PHPUnit: Assert json element exists without defining the value

Tags:

I'm sending a post request in a test case, and I want to assert that a specific element, let's say with key 'x' exists in the response. In this case, I can't say seeJson(['x' => whatever]); because the value is unknown to me. and for sure, I can't do it with seeJson(['x']);.

Is there a way to solve this?

If it matters: Laravel: v5.2.31 PHPUnit: 5.3.4

like image 364
Milad.Nozari Avatar asked May 16 '16 10:05

Milad.Nozari


2 Answers

May it will be helpful for anyone else. You can write this test for your check response json structure

$this->post('/api/login/', [
        'email' => '[email protected]',
        'password' => '123123123',
    ])->assertJsonStructure([
        'status',
        'result' => [
            'id',
            'email',
            'full_name',
        ],
    ]);
like image 50
Илья Савич Avatar answered Sep 22 '22 18:09

Илья Савич


Although it's not optimal at all, I chose to use this code to test the situation:

$this->post(URL, PARAMS)->see('x');

X is a hypothetical name, and the actual element key has a slim chance of popping up in the rest of the data. otherwise this nasty workaround wouldn't be practical.

UPDATE:

Here's the solution to do it properly:

public function testCaseName()

{
    $this->post(route('route.name'), [
        'param1' => 1,
        'param2' => 10,
    ], [
        'headers_if_any' => 'value'
    ]);

    $res_array = (array)json_decode($this->response->content());

    $this->assertArrayHasKey('x', $res_array);
}
like image 28
Milad.Nozari Avatar answered Sep 19 '22 18:09

Milad.Nozari