Laravel断言杰森失败了

时间:2019-05-13 11:05:54

标签: laravel phpunit

我对此测试有疑问:

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

我不明白什么错误:

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.',
-  ),
)

似乎JSON断言在答案之内。

1 个答案:

答案 0 :(得分:1)

assertJson在这种情况下不起作用,因为您要查找的数据在errors下。

您可以包装数组并使用"errors"对其进行键入:

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

或者您也可以使用assertJsonFragment来尝试将json的任何部分与您提供的内容进行匹配:

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