enfix
enfix

Reputation: 6970

Laravel assertJson failed

i have a problem to this test:

$this->json('POST', 'api/login')
        ->assertStatus(422)
        ->assertJson([
            'email' => ['The email field is required.'],
            'password' => ['The password field is required.'],
        ]);

And I don't understand what the error:

Unable to find JSON: 

[{
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}]

within response JSON:

[{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}].


Failed asserting that an array has the subset Array &0 (
    'email' => Array &1 (
        0 => 'The email field is required.'
    )
    'password' => Array &2 (
        0 => 'The password field is required.'
    )
).
--- Expected
+++ Actual
@@ @@
    0 => 'The password field is required.',
    ),
),
-  'email' => 
-  array (
-    0 => 'The email field is required.',
-  ),
-  'password' => 
-  array (
-    0 => 'The password field is required.',
-  ),
)

It seems that the JSON assert is within the answer.

Upvotes: 3

Views: 2893

Answers (2)

Ngugi Kiarie
Ngugi Kiarie

Reputation: 1448

Confirm that the string you're checking against matches the one in the assert method.

I had the same problem as illustrated below

The string I was checking against: Reimbursement updated successfully! The string in my assert statement: Reimbursement updated successfully

Note the missing !, the two strings/values have to be an exact match!

~Regards

Upvotes: 0

Rwd
Rwd

Reputation: 35180

assertJson won't work in the case as the data you're looking for is under errors.

You can either wrap your array and key it with "errors":

->assertJson([
    'errors' => [
        'email'    => ['The email field is required.'],
        'password' => ['The password field is required.'],
    ],
])

or you could instead use assertJsonFragment which will try and match any part of the json to what you've provided:

->assertJsonFragment([
    'email' => ['The email field is required.'],
    'password' => ['The password field is required.'],
])

Upvotes: 6

Related Questions