'Which assert method should I use to pass my api store test?
I am trying to pass my testStoreUser() method and am having issues with which assert statement to use. The password I am using the API route instead to the server route with hash. Here is my testStoreUser():
public function testStoreUser()
{
//Arrange
$data = [
'data' => [
'name' => 'Testing Name',
'email' => '[email protected]',
'password' => 'Harley81',
],
];
//Act
$response = $this->postJson('/api/users/', $data);
//Assert
$response
->assertStatus(201)
->assertJsonStructure([
'data' => [
'name',
'email',
'password',
]
]);
$this->assertDatabaseHas('users', $data['data']);
}
Here is my api/user controller specifically the store function:
/**
* Store a newly created user in storage.
*
* @param Request $request
* @return UserResource
*/
public function store(Request $request): UserResource
{
$validated = $request->validate([
'data' => 'required|array',
'data.name'=> 'required|string',
'data.email'=> 'required|string',
'data.password' => ['required', Password::min(8)->mixedCase()],
]);
$user = new User();
$user->fill($validated['data'])->saveOrFail();
return new UserResource($user);
}
And this is current error I am getting:
Failed asserting that an array has the key 'password'.
/var/www/html/vendor/laravel/framework/src/Illuminate/Testing/AssertableJsonString.php:256
/var/www/html/vendor/laravel/framework/src/Illuminate/Testing/AssertableJsonString.php:241
/var/www/html/vendor/laravel/framework/src/Illuminate/Testing/AssertableJsonString.php:254
/var/www/html/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:795
/var/www/html/tests/Feature/UserApiTest.php:49
Solution 1:[1]
I just needed this in my test.
$response
->assertStatus(201)
->assertJson([
'data' => [
'name' => $data['data']['name'],
'email' => $data['data']['email'],
]
]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex V |
