I’m working on a tdd project where I simply want to make sure that the password is not returned by mistake. here is the test I wrote.
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
}
I know for a fact that password is being returned but why does the assertJsonMissing does not work when I only pass the key? if it’s not used for that, what is the correct way to check that a data key is missing?
2
Answers
Actually
assertJsonMissing
is for test key, not value!You can make a special method for this problem or maybe see this:
https://laravel.com/docs/10.x/http-tests#assert-json-fragment
assertJsonMissing(array $data)
tries to find$data
whithin the json you returned.The difference between
assertJsonMissing(['password'])
andassertJsonMissing(['password' => 'something'])
is the following:assertJsonMissing(['password'])
tries to find{"0": "password"}
in your json if the json returned is an object.assertJsonMissing(['password' => 'something'])
tries to find{"password": "something"}
inside the returned json object.Here are a couple of alternatives.
assertJsonMissingPath('password')
.