Laravel测试assertJsonMissing不能只对key工作.为什么?



我正在一个tdd项目中工作,我只是想确保不会错误地返回密码。下面是我写的测试。

public function testInfoMethodJsonStructure() {
$user = User::factory()->create();
$response = $this
->actingAs($user)
->get('/api/profile/info');
$response->assertStatus(200);
$response->assertJsonStructure(['name', 'fullname', 'email']);
$response->assertJsonMissing(['password']); // this passes
$response->assertJsonMissing(['password' => $user->password]); // this does not pass
}

我知道一个事实,密码正在返回,但为什么assertJsonMissing不工作,当我只传递密钥?如果没有使用它,那么检查数据键是否丢失的正确方法是什么?

assertJsonMissing(array $data)尝试在您返回的json中找到$data

assertJsonMissing(['password'])assertJsonMissing(['password' => 'something'])的差异如下:

  • assertJsonMissing(['password'])试图找到{"0": "password"}在你的json如果json返回的是一个对象。
  • assertJsonMissing(['password' => 'something'])试图在返回的json对象中找到{"password": "something"}

这里有几个选择。

  • assertJsonMissingPath('password').
  • 流畅的json断言。
$response
->assertJson(fn (AssertableJson $json) =>
$json->hasAll(['name', 'fullname', 'email'])
->missing('password')
);

实际上assertJsonMissing是用于测试键,而不是值!你可以用一个特殊的方法来解决这个问题,或者可以这样看:https://laravel.com/docs/10.x/http-tests assert-json-fragment

最新更新