laravel 在多个字段上测试 assertJsonValidationErrors 误报

laravel test assertJsonValidationErrors false positive on multiple fields

  $data = [
        'name' => '', // required field
        'email' => '' // required field
  ];
  // or $data = [];

  $this->postJson('api/users', $data)
        ->assertStatus(422)
        ->assertJsonValidationErrors(
            ['name']
        );

我正在编写验证字段的测试。上面的测试将通过,我预计它会失败,因为名称和电子邮件字段都是必需的,并且应该都在验证错误中。如何强制 assertJsonValidationErrors 检查错误包中的所有字段。谢谢

经过一番思考并深入研究 laravel 文档,我找到了一个解决方案:使用 assertJson 而不是 assertJsonValidationErrors

  $data = [
        'name' => '', // required field
        'email' => '' // required field
  ];
  // or $data = [];

  $this->postJson('api/users', $data)
        ->assertStatus(422)
        ->assertJson(function (AssertableJson $json) use ($data) {
                $json->has('message')
                    ->has('errors', 2) // it will check the exact size of the errors bag
                    ->whereAllType([
                        'errors.name' => 'array',
                        'errors.email' => 'array',
                    ]);
            });