Home > Software design >  Laravel unit testing json response
Laravel unit testing json response

Time:12-20

I have the following test in my app. However the response isn't passing the test, and I can't see why...

public function test_get()
{
    $user = $this->signInAsUser();
    
    $product = factory('App\Models\Product')->create();

    factory('App\Models\Stock')->create([
        'product_id' => $product->id,
        'qty' => $qty = rand(1, 100),
    ]);

    $this->json('GET', '/api/stock', , ['Accept' => 'application/json'])
        ->assertStatus(200)
        ->assertJson([
            'data' => [
                'product_id' => "$product->id",
                'stock' => "$qty"
            ]
        ]);
}

This produces the following from PHPUnit:

Unable to find JSON: 

[{
    "data": {
        "product_id": "1",
        "stock": "55"
    }
}]

within response JSON:

[{
    "data": [
        {
            "product_id": "1",
            "stock": "55"
        }
    ]
}].


Failed asserting that an array has the subset Array &0 (
    'data' => Array &1 (
        'product_id' => '1'
        'stock' => '55'
    )
).

The assertion is failing the test and I can't see why as the JSON looks the same to me...

CodePudding user response:

You're asserting your JSON response is a single object, whereas it is an array of objects. Try using assertJsonFragment rather than assertJson.

  • Related