Slowly going crazy…
I want to use PEST for laravel API testing – I’m suspecting this is bad.
Tests work fine, until I hit routes that need token auth. This seems impossible using PEST as it keeps getting 404 errors.
Here is my current attempt:
use AppModelsChemical;
use IlluminateFoundationTestingRefreshDatabase;
use AppModelsUser;
uses(RefreshDatabase::class);
test('it retrieves a list of chemicals', function (){
$chemical = Chemical::factory()->create();
$user = User::factory()->create();
$token = $user->createToken('api-token')->plainTextToken;
$this->getJson('/v1/chemicals', ['Authorization' => 'Bearer ' . $token])
->assertStatus(200)
->assertJson([
'data' => [
[
'id' => $chemical->id,
'name' => $chemical->name,
'extra' => $chemical->extra,
'cas_number' => $chemical->cas_number,
]
]
]);
});
This fails with:
ChemicalControllerTest > it retrieves a list of chemicals
Expected response status code [200] but received 404.
Failed asserting that 200 is identical to 404.
using dd – I see that a valid token does get generated – but it seems to barf.. Weirdly it seems to nuke all seeded users as well..
This curl works fine
curl --request GET
--url http://laravel-api.test/api/v1/chemicals
--header 'Accept: application/json'
--header 'Authorization: Bearer 1|laravel_sanctum_HbPJpzXxpxU2EUqS9wkflt0h9OUPlaMoWQWUYtKseedfe14f'
What am I getting wrong? Or should I manually login to get a token and then save it into my code?
I did originally want to have some kind of global function to carry a token so that I didn’t have to write boilerplate to create tokens…
2
Answers
core problem is that PEST didn't read my mind and realise the route starts with '/api'
However a better way to insert the route is to used the route name (assuming you named your route) Then you get
Try setting your app url to localhost in your phpunit.xml file
<server name="APP_URL" value="http://localhost"/>
And clear your config cache
php artisan config:cache