murilo's avatar
Level 10

do I have to name the route to access it in Pest via Post or Get ?

hello , do I have to name routes to access it in Pest ?

I ha this route -

this works

test('my test', function () {
          postJson(route('login'), $data)->json();
});

but this does not work -

test('my test', function () {
          postJson( /api/login, $data)->json();
});

I tryed as well -

test('my test', function () {
          postJson( http://localhost/api/login, $data)->json();
});

does not work as well

0 likes
2 replies
LaryAI's avatar
Level 58

In Pest PHP, you do not necessarily have to name your routes to access them in your tests. However, using named routes can make your tests cleaner and more maintainable. The issue you're encountering in your examples where the tests do not work is likely due to syntax errors in how you're specifying the URL in the postJson function.

Here's how you can correctly use both named and unnamed routes in your Pest tests:

Using Named Routes

First, ensure your route is named in your routes file (e.g., web.php or api.php):

Route::post('/api/login', 'AuthController@login')->name('login');

Then, you can reference this route in your Pest test using the route() helper:

test('my test with named route', function () {
    $data = ['email' => '[email protected]', 'password' => 'password'];
    postJson(route('login'), $data)->assertStatus(200);
});

Using Unnamed Routes

If you prefer not to use named routes, you can directly use the URL. Make sure to pass the URL as a string:

test('my test with unnamed route', function () {
    $data = ['email' => '[email protected]', 'password' => 'password'];
    postJson('/api/login', $data)->assertStatus(200);
});

Common Mistakes

  1. Incorrect URL Format: Ensure the URL is a string. In your example, you missed the quotes around the URL.
  2. Full URL Usage: While you can use the full URL, it's generally not necessary and can lead to errors if your environment changes. If you need to use the full URL, ensure it's correctly formatted as a string:
test('my test with full URL', function () {
    $data = ['email' => '[email protected]', 'password' => 'password'];
    postJson('http://localhost/api/login', $data)->assertStatus(200);
});

Remember to always check for syntax errors and ensure that your routes are correctly defined in your Laravel application. Also, using assertions like assertStatus(200) can help you verify that your requests are not only being sent but are also receiving the expected responses.

gych's avatar

You don't have single quotes around the route path

test('my test', function () {
	postJson('/api/login', $data)->json();
});

Please or to participate in this conversation.