skip to Main Content

I have a test, which testing displaying deals. This test failed and show error Failed asserting that an array has the key 'user_id'.` I don’t know reason why this error is

public function a_test_display_deals()
{
    $user = User::factory()->create();

    $response = $this->postJson(route('deals.index'), [
        'user_id'         => 1,
        'contract_number' => 26308,
        'amount' => 2681.00
    ]);
    $response->assertJsonStructure([
                'user_id',
                'contract_number',
                'amount'
    ]);

}

2

Answers


  1. You can check this by asserting with the status code for example i’m assuming you’re sending 200 OK response on post request success.

    public function a_test_display_deals()
    {
        $user = User::factory()->create();
    
        $response = $this->postJson(route('deals.index'), [
            'user_id'         => 1,
            'contract_number' => 26308,
            'amount' => 2681.00
        ]);
    
        $response->assertStatus(200);
    }
    

    This helps not only in checking the json fragment but also the Status for post response.

    Edit:

    Only asserting the Status is 200 or whatever you’ve set is also fine for testing apis.

    Login or Signup to reply.
  2. Post parameters are not necessarily the same as API returns.

    Look in your controller what are the attributes that are returning and compare the answers with them, not with post parameters. The chance that a collection of models is returned is great. They might even be the same, but it’s extremely rare.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search