Let's look at another trick: how to view the test errors slightly differently.
Imagine you have a test to check if the record is being seen on the page.
use App\Models\User;use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); test('homepage contains table product', function () { $product = Product::create([ 'name' => 'table', 'price' => 100, ]); actingAs($this->user) ->get('/products') ->assertOk() ->assertSeeText($product->name);});
In the Controller, you left a typo for the variable.
use App\Models\Product;use Illuminate\View\View; class ProductController extends Controller{ public function index(): View { $product = Product::all(); return view('products.index', compact('products')); }}
When you run the test, it gives the error Expected response status code [200] but received 500
. It's an Exception in the Controller.
We can improve this error message.
There are two ways. The first way is to use the --without-exception-handling
flag when running the tests.
php artisan test --without-exception-handling
Notice: This flag only works using Pest, not with PHPUnit.
When the test is being run, it shows the exact line where the error is in the Controller.
The second way is to add the $this->withoutExceptionHandling()
. You can add it directly to the test where you want it to run without Exception handling.
use App\Models\User;use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); test('homepage contains table product', function () { $this->withoutExceptionHandling(); $product = Product::create([ 'name' => 'table', 'price' => 100, ]); actingAs($this->user) ->get('/products') ->assertOk() ->assertSeeText($product->name);});
Or run it before each test.
use App\Models\User;use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create(); $this->withoutExceptionHandling(); }); // ...
Or add it to the Base Test class and run it for every test.
tests/TestCase.php:
use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase{ protected function setUp(): void { parent::setUp(); $this->withoutExceptionHandling(); }}
This "without exception" trick points the error moment into the Controller or into where it actually happens instead of showing you the test result with the entire trace.
Sometimes, it may be more beneficial, but it's your personal preference. It's one way of making the debugging process of the failed test easier.