Home > Back-end >  Laravel 9 API Testing: Route [XXXXXX] not defined
Laravel 9 API Testing: Route [XXXXXX] not defined

Time:08-04

I'm creating a simple API using Laravel 9. When I access http://127.0.0.1:8000/api/categories from my REST client (insomnia) I'm getting the json response that I'm expecting. I started writing tests for my API. I'm trying out Pest, so I've got the following test:

use function Pest\Laravel\getJson;

it('returns empty when there are no elements in the system', function() {

    $categories = $this->getJson(route('categories'))->json('data');

    dd($categories);
});

I'm getting an error that says:

Route [categories] not defined.

I also tried: $this->getJson(route('api/categories'))->json('data');

and tried php artisan route:clear as well but none of those made any difference.

Thanks.

CodePudding user response:

Ensure that your /categories endpoint is named in your api.php routes file.

For example...

Route::get('/categories', [CategoriesController::class, 'index'])->name('categories');

We name routes so that we can change the URI of the route internally at the routes level without having to find and replace every instance of it in the code at once. Insomnia, being an external tool, won't care about your route name.

CodePudding user response:

The answer voted is super correct. However if you want to stick to laravel standarts and use it's original names, you can try: php artisan route:list This will give you all the routes list and their names & params.

  • Related