Search code examples
jsonlaravelphpunit

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


I'm sending a post request in a test case, and I want to assert that a specific element. Let's say I have a key x which exists in the response. In this case, I can't say seeJson(['x' => whatever]); because the value is unknown. 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


Solution

  • 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);
    }