Debug Methods Built Into Laravel’s TestResponse

Looking at Laravel’s HTTP Tests documentation carefully, you’ll notice some useful helpers built into the TestResponse class to debug HTTP responses. This class recently had some internal updates to these methods in the way of the Laravel 11's Dumpable Trait, and I thought it would be a good time to revisit these useful helpers:

$response = $this->get('/');


These methods have a dd() counterpart too, which will “die and dump” response values:


These methods are helpful shortcuts to just doing this yourself in a test:

// or 

However, where these methods shine is when you modify an existing test that chains various assertions on the TestResponse instance:

$this->postJson(route('', $post))
    ->assertJson(['created' => true]);

Let’s say that assertSessionHasNoErrors() fails, and I want to debug. I’ve noticed when I come across a chain that doesn’t assign the response, that I assign the response to a local variable like so:

$response = $this->postJson(route('', $post));


    ->assertJson(['created' => true]);

I will not argue whether you should chain assertions and never assign a local variable—that is more of a style preference—but you’ll come across situations where no local variable is assigned. Using these debug methods, we can quickly debug right before a test failure:

$this->postJson(route('', $post))
+   ->dumpSession()
    ->assertJson(['created' => true]);

These debug helpers are handy when you want to debug the response somewhere between various assertions without grabbing the TestResponse instance in a local variable.

Learn More

These features (and more) are covered in the Laravel documentation for HTTP Tests along with other useful TestResponse features that make asserting JSON a breeze.

The post Debug Methods Built Into Laravel’s TestResponse appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

Read more

© 2024 Extly, CB - All rights reserved.