Adding http testing on laravel 10 site I got 401 error :
✘ 1 ItemIsAdded
┐
├ Expected response status code [201] but received 401.
├ Failed asserting that 201 is identical to 401.
│
│ /project/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:147
│ /project/tests/Feature/ItemsCrudTest.php:60
│ /project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:174
when in test I use actingAs method, but seems it does not work :
public function test_1_ItemIsAdded()
{
// Test Data Setup
\Log::info(varDump(self::$loggedUser, ' -1 self::$loggedUser::'));
$itemModel = Item::factory()->make([
'user_id' => self::$loggedUser->id
]);
// Test Action
$response = $this
->actingAs(self::$loggedUser, 'api')
->postJson(route('items.store'), $itemModel->toArray());
$response
->assertStatus(JsonResponse::HTTP_CREATED); // 201 - ERROR POINTS TO THIS LINE
Calling actingAs I set 2nd parameter 'api', but it does not work.
This request works ok under POSTMAN, 401 error only in http testing and I can not get why? In config/auth.php :
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
In routes/api.php I have :
use App\Http\Controllers\Api\ItemController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::middleware('auth:sanctum') ->group(function () {
Route::apiResource('items', ItemController::class);
...
I have .env.testing file, but have I to add some specific options to it ?
How to make tests working ?
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.3",
Thanks in advance!