Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel 9 API Testing: Route [XXXXXX] not defined

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading