Automated testing in Laravel is one of the most powerful tools for ensuring your application works exactly as expected. Not only does it validate your code's behavior, it also helps you keep it clean, secure, and scalable as the project grows. In this practical guide, I will show you what PHPUnit is, how to implement unit and feature tests with PHPUnit and Pest—the two official options in the Laravel ecosystem—how to migrate between them frictionlessly, and how to test real modules with Livewire and Inertia.
If you have already left classic performance issues behind, such as Eager loading and lazy loading in Laravel, the next natural step is backing your application with automated tests.
🧠 What Is PHPUnit and What Are Tests in Laravel?
Before writing code, it is worth clarifying the core concepts. PHPUnit is the standard, longest-standing testing framework in the PHP ecosystem. It comes built into Laravel by default and lets you write test classes to verify that your methods, routes, queries, and views respond as they should. Meanwhile, Pest (pestphp) is a modern layer built on top of the exact same PHPUnit engine that offers a far more minimalist and expressive syntax.
Unit tests, specifically, are small pieces of code that verify each part of your application (a model, a helper, a service class, etc.) works properly in isolation. In Laravel, this entire workflow integrates natively through the php artisan test command and ready-to-use assertion methods.
Types of Tests in Laravel
Within the Laravel ecosystem, we can distinguish three major levels of testing:
- Unit tests (
Unit): verify individual functions, classes, or methods in isolation, without depending on the database or full HTTP requests. - Integration or functional tests (
Feature): evaluate how multiple components interact together: routes, middleware, controllers, models, database, and HTML or JSON responses. - End-to-End tests (E2E): simulate a user's complete real workflow in the browser, for instance using Laravel Dusk or Pest's browser plugin.
TDD in Action (and How to Leverage AI)
In my experience, applying TDD (Test-Driven Development) in Laravel completely changes the way you program. When I started building modules like the dashboard, I wrote the tests first, and that allowed me to define clear rules about what each route or controller had to do before writing the final logic.
Today, even when leaning on artificial intelligence, you can follow this same philosophy: ask it, based on a module's requirements, to generate the tests first and then implement the logic needed to make them pass. That way you gain consistency and set clear boundaries around the scope of each feature.
Importance of Automated Tests: Why Write Them?
Automated tests are a cornerstone in any professional application, regardless of the technology stack. Every time you add a new feature or refactor existing code, they let you validate the entire system in seconds by running a single command, instead of repeating manual checks over and over in the browser.
Furthermore, in projects with many endpoints or modules—such as REST API methods and their dependencies—having a green test suite gives you fast initial confirmation that nothing broke. If a test fails, you immediately know which file and line to inspect, whether to fix a bug in the app or update the test if business rules changed.
It pays to stay grounded: tests are not infallible. Passing 100% of your tests does not guarantee your app is bug-free, because everything depends on the quality and edge cases you covered. Even so, it is the best early indicator of project health; in fact, code that is easy to test is almost always a sign of good architecture.
What Should You Test in a Laravel Application?
Across both unit and integration (Feature) tests, some of the highest-return areas to cover include:
- Controllers and access permissions (roles, policies, and middleware).
- View responses (Blade, Livewire, or Inertia props).
- HTTP status codes (
200,201,302,403,404,422). - Requests across different HTTP verbs (
GET,POST,PUT,PATCH,DELETE). - Form validation and error handling in session or JSON.
helperfunctions, services, and isolated business logic.
To cover all of this, Laravel officially supports two testing frameworks: PHPUnit and Pest.
⚙️ Setting Up the Testing Environment in Laravel
When you create a new Laravel project, the tests/ directory is generated automatically, underscoring how much importance the framework places on testing. Even starting in Laravel 11, when the directory structure was significantly streamlined, tests/ remained intact at the project root.
Inside tests/ you will find two main subdirectories along with ready-to-run sample files such as ExampleTest.php:
tests/Unit: meant for unit tests of classes, models, facades, or helpers in isolation.tests/Feature: meant for integration tests involving routes, controllers, database queries, JSON responses, or views.
Regardless of whether you chose PHPUnit or Pest when installing Laravel, the logical flow is the same; only the syntax changes. To run your tests in the terminal, you can use any of these commands:
$ vendor/bin/phpunitIf you are working with Pest:
$ vendor/bin/pestOr the unified Artisan command, which works identically for both:
$ php artisan testAs for global configuration, phpunit.xml defines environment variables and directories for PHPUnit, while Pest adds tests/Pest.php to register global settings, helpers, and shared traits.
Additionally, you can create a
.env.testingfile in your project root to isolate environment variables in the test environment. Laravel will automatically load it instead of the regular.envwhen running Pest, PHPUnit, or commands with the--env=testingflag.
Database in Testing Mode: Configure DB_CONNECTION and DB_DATABASE in phpunit.xml
A very common beginner mistake is running tests against the same database used for local development. If you do that, cleanup traits will wipe your local data every time you run tests. Tests must always run on an isolated database—never your development database, and certainly never production.
To avoid overwriting your development database and gain substantial speed, open phpunit.xml in the project root. By default, you will see these two commented lines:
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<!-- <env name="DB_CONNECTION" value="sqlite"/> -->
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
<env name="MAIL_MAILER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>Uncommenting them tells Laravel to use sqlite as the driver (DB_CONNECTION) and :memory: as the database (DB_DATABASE). This means all test migrations and queries run directly in RAM without touching your local database and at far higher speed:
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="MAIL_MAILER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>Once the database is isolated, you can use the RefreshDatabase trait (in your PHPUnit classes or globally in tests/Pest.php) to guarantee each test starts with clean tables:
uses(TestCase::class, RefreshDatabase::class)->in('Feature');Factories and Seeders for Test Data
With a clean database before each test, you need a fast way to generate records. That is what Eloquent factories are for:
Category::factory(10)->create();In my daily workflow, I call factory() right at the start of each test to populate the categories, users, or posts needed before testing a CRUD flow or paginated listing.
🧩 PHPUnit Tutorial in Laravel: First Steps and Unit Tests
To create a test file via Artisan, you have two main options. If you want a unit test in tests/Unit, pass the --unit flag:
$ php artisan make:test MathOperationsTest --unitIf you want a feature test in tests/Feature, omit that flag:
$ php artisan make:test PostTest(If you have Pest installed in the project, you can append --pest to either command to generate the boilerplate using Pest syntax.)
Understanding Unit Tests with a Simple Example
To see how the assertion engine works without distractions, let us create a simple helper class with math operations in app/Utils/MathOperations.php:
<?php
namespace App\Utils;
class MathOperations
{
public function add($a, $b)
{
return $a + $b;
}
public function subtract($a, $b)
{
return $a - $b;
}
public function multiply($a, $b)
{
return $a * $b;
}
public function divide($a, $b)
{
return $a / $b;
}
}Now let us generate its unit test using php artisan make:test MathOperationsTest --unit. This creates tests/Unit/MathOperationsTest.php, where we define one test method per operation (to keep this first exercise simple, you can import App\Utils\MathOperations or define the class right inside the same file):
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
// use App\Utils\MathOperations;
class MathOperations
{
public function add($a, $b)
{
return $a + $b;
}
public function subtract($a, $b)
{
return $a - $b;
}
public function multiply($a, $b)
{
return $a * $b;
}
public function divide($a, $b)
{
return $a / $b;
}
}
class MathOperationsTest extends TestCase
{
public function test_add(): void
{
$mathOperations = new MathOperations();
$result = $mathOperations->add(2, 3);
$this->assertEquals(5, $result);
}
public function test_subtract(): void
{
$mathOperations = new MathOperations();
$result = $mathOperations->subtract(5, 3);
$this->assertEquals(2, $result);
}
public function test_multiply(): void
{
$mathOperations = new MathOperations();
$result = $mathOperations->multiply(5, 3);
$this->assertEquals(15, $result);
}
public function test_divide(): void
{
$mathOperations = new MathOperations();
$result = $mathOperations->divide(8, 2);
$this->assertEquals(4, $result);
}
}In this example we have four test methods—one for each operation in
MathOperations. This clearly shows the heart of testing:assertmethods (assertions), such asassertEquals(), which compare an expected value against the actual result.
You can check the full list of HTTP assertions available in Laravel in the official documentation: https://laravel.com/docs/master/http-tests#response-assertions. Do not worry about memorizing all of them: in day-to-day work you will rely on a core handful.
To run the tests, execute in your terminal:
$ vendor/bin/phpunitYou will get output similar to this:
Time: 00:00.850, Memory: 42.50 MB
OK (29 tests, 65 assertions)Now, what happens if we intentionally introduce a bug in MathOperations—for instance, adding the $a parameter twice and ignoring $b?
public function add($a, $b)
{
return $a + $a;
}Running vendor/bin/phpunit again immediately alerts us:
/MathOperationsTest.php:47
FAILURES!
Tests: 29, Assertions: 65, Failures: 1.However, notice an important detail about why tests are not magic: if, while keeping that exact same bug in add(), our test had evaluated add(2, 2) against 4:
public function test_add(): void
{
$mathOperations = new MathOperations();
$result = $mathOperations->add(2, 2);
$this->assertEquals(4, $result);
}The test would pass!
Time: 00:00.733, Memory: 42.50 MB
OK (29 tests, 65 assertions)Even though the implementation is broken. That is why I always say tests do not prove the total absence of bugs—only that the code satisfies the scenarios you chose to verify. With that foundation clear, let us move on to testing real Laravel modules.
Common Assertions and HTTP Requests in Laravel
Laravel applications revolve around routes and controllers responding to HTTP requests. To test them, our classes in tests/Feature extend Tests\TestCase, which provides helper methods for every HTTP verb: get(), post(), put(), patch(), and delete().
Under the hood, assertions are advanced conditionals inspecting the response for you. Here are the most commonly used ones:
assertStatus(404): verifies that the response returns a specific HTTP status code.assertOk(): shorthand for asserting the response has HTTP status code200.assertJson(): validates that the response is JSON and contains the expected structure or data.assertRedirect(): checks that the request redirects to another route or URL.assertSee('Text'): verifies that the given string appears in the response HTML or content.assertDontSee('Text'): confirms that specific text is absent from the response.assertViewIs('view'): validates that the route returned the exact Blade view specified.assertViewHas('key'): checks that the view received a specific variable and optionally evaluates its value.assertValid(): verifies that there are no validation errors on the given fields.assertDatabaseHas('table', $data): confirms that a record matching those values exists in the database.
Basic Structure with PHPUnit and the setUp() Method
When testing modules protected by authentication, roles, or permissions (for instance, with Spatie Laravel Permission), repeating admin user creation in every test method bloats the file. That is what setUp() is for in PHPUnit: a method that runs automatically before each test.
In tests/Feature/dashboard/PostTest.php, we can prepare the user, role, and permissions like this, using $this->actingAs($user) to authenticate them:
<?php
namespace Tests\Feature\dashboard;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class PostTest extends TestCase
{
use DatabaseMigrations;
protected function setUp(): void
{
parent::setUp();
User::factory(1)->create();
$user = User::first();
$role = Role::firstOrCreate(['name' => 'Admin']);
Permission::firstOrCreate(['name' => 'editor.post.index']);
Permission::firstOrCreate(['name' => 'editor.post.create']);
Permission::firstOrCreate(['name' => 'editor.post.edit']);
Permission::firstOrCreate(['name' => 'editor.post.delete']);
$role->syncPermissions([1, 2, 3, 4]);
$user->assignRole($role);
$this->actingAs($user); // You can also chain ->withSession(['role' => 'Admin']) if needed
}
public function test_index(): void
{
$this->get(route('post.index'))
->assertOk()
->assertViewIs('dashboard.post.index')
->assertSee('Dashboard');
}
}If you also need to simulate specific session variables alongside authentication, you can chain actingAs($user) with withSession([...]) according to your middleware requirements.
Essential Assertion Methods in Action
assertOk() and assertStatus(404) — HTTP Status Codes
These are the first assertion methods you should master. assertOk() is equivalent to writing assertStatus(200): status code 200 indicates the request succeeded. For nonexistent routes, redirects, or denied access, we reach directly for assertStatus(404), assertRedirect(), or assertForbidden().
assertSee('Text') — Visible Content in the Response
Another indispensable method is assertSee(), which checks what text the user actually sees in the rendered view. If we test a post detail view, we first create the record along with its dependencies and then verify that the response contains the title, content, and associated category.
assertViewHas('posts') — Data Passed to the View
When working with controllers that return a Blade view, assertViewHas() lets us validate not only that the variable reached the view (for instance, plural posts), but also that its value or pagination structure matches exactly what the controller sent.
And to confirm that write operations actually persisted or deleted records, we pair it with assertDatabaseHas('posts', $data) and assertDatabaseMissing('posts', $data).
⚡ PHPUnit vs Pest in Laravel: Comparison and Step-by-Step Migration
Pest (pestphp) is a modern, minimalist alternative to PHPUnit that is 100% compatible with everything already in Laravel. In fact, Pest uses PHPUnit under the hood, so you lose no capabilities; its main advantage lies in offering a cleaner, functional, and easier-to-read syntax.
⚖️ PHPUnit vs Pest: Quick Comparison
| Aspect | PHPUnit | Pest PHP |
|---|---|---|
| Syntax | Traditional, class-oriented (extends TestCase) with methods | Modern and minimalist using global functions (test() or it()) |
| Test Setup | Protected method setUp(): void | Functional hook beforeEach(function () { ... }) |
| Learning Curve | Slightly more verbose and formal | Very approachable and fast to write |
| Laravel Compatibility | Full (native) | Full (powered by PHPUnit internally) |
| Approach | Formal and structured | Lightweight, expressive, and chainable (expect()) |
| Best For | Large teams or established legacy projects | Greenfield projects or teams prioritizing speed and readability |
In my experience, neither option is universally "better." If you already maintain a large project with hundreds of classes written in PHPUnit, sticking with PHPUnit is completely valid and stable. But if you are starting a project from scratch or prefer a more fluid syntax, working with Pest is a pleasure.
Key Differences When Migrating from PHPUnit to Pest
- In Pest you do not declare classes extending
TestCase; you write global functions usingtest('description', function () { ... })orit('does something', function () { ... }). - The
setUp()method (and@testannotations) are replaced bybeforeEach()and calls totest(). - Laravel's HTTP assertions (
assertOk(),assertViewIs(),assertDatabaseHas(), etc.) are written identically. - To validate substrings inside strings, you can use
assertStringContainsString()for literal text orassertMatchesRegularExpression()when evaluating a regex pattern.
Let us look at a quick example comparing both approaches on an API endpoint:
With PHPUnit:
class CategoryTest extends TestCase
{
public function test_all(): void
{
$this->get('/api/category/all')
->assertOk()
->assertJson([...]);
}
}With Pest:
test('test all', function () {
$this->get('/api/category/all')
->assertOk()
->assertJson([...]);
});When migrating my own tests, I found that the underlying logic is identical: only the wrapper changes. Plus, beforeEach() is super convenient for setting up users, roles, and authentication before every test case:
beforeEach(function () {
User::factory(1)->create();
$this->user = User::first();
$this->actingAs($this->user);
});Complete CRUD Comparison: PHPUnit vs Pest
Here is the full CRUD test file for PostTest written in PHPUnit so you can compare it line by line against its Pest equivalent:
Here is the complete CRUD test file for PostTest written in PHPUnit so you can compare it line by line against its Pest equivalent:
<?php
namespace Tests\Feature\dashboard;
use App\Models\Category;
use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class PostTest extends TestCase
{
use DatabaseMigrations;
public User $user;
protected function setUp(): void
{
parent::setUp();
User::factory(1)->create();
$this->user = User::first();
$role = Role::firstOrCreate(['name' => 'Admin']);
Permission::firstOrCreate(['name' => 'editor.post.index']);
Permission::firstOrCreate(['name' => 'editor.post.create']);
Permission::firstOrCreate(['name' => 'editor.post.update']);
Permission::firstOrCreate(['name' => 'editor.post.destroy']);
$role->syncPermissions([1, 2, 3, 4]);
$this->user->assignRole($role);
$this->actingAs($this->user);
}
public function test_index(): void
{
User::factory(1)->create();
$user = User::first();
$this->actingAs($user);
Category::factory(3)->create();
User::factory(3)->create();
Post::factory(20)->create();
$response = $this->get(route('post.index'))
->assertOk()
->assertViewIs('dashboard.post.index')
->assertSee('Dashboard')
->assertSee('Create')
->assertSee('Show')
->assertSee('Delete')
->assertSee('Edit')
->assertSee('Id')
->assertSee('Title');
$this->assertInstanceOf(LengthAwarePaginator::class, $response->viewData('posts'));
}
public function test_create_get(): void
{
Category::factory(10)->create();
$response = $this->get(route('post.create'))
->assertOk()
->assertSee('Dashboard')
->assertSee('Title')
->assertSee('Slug')
->assertSee('Content')
->assertSee('Category')
->assertSee('Description')
->assertSee('Posted')
->assertSee('Send')
->assertViewHas('categories', Category::pluck('id', 'title'))
->assertViewHas('post', new Post());
$this->assertInstanceOf(Post::class, $response->viewData('post'));
$this->assertInstanceOf(Collection::class, $response->viewData('categories'));
}
public function test_create_post(): void
{
Category::factory(1)->create();
$data = [
'title' => 'Title',
'slug' => 'title',
'content' => 'Content',
'description' => 'Content',
'category_id' => 1,
'posted' => 'yes',
'user_id' => $this->user->id,
];
$this->post(route('post.store', $data))
->assertRedirect(route('post.index'));
$this->assertDatabaseHas('posts', $data);
}
public function test_create_post_invalid(): void
{
Category::factory(1)->create();
$data = [
'title' => '',
'slug' => '',
'content' => '',
'description' => '',
// 'category_id' => 1,
'posted' => '',
];
$this->post(route('post.store', $data))
->assertRedirect('/')
->assertSessionHasErrors([
'title' => 'The title field is required.',
'slug' => 'The slug field is required.',
'content' => 'The content field is required.',
'description' => 'The description field is required.',
'posted' => 'The posted field is required.',
'category_id' => 'The category id field is required.',
]);
}
public function test_edit_get(): void
{
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$response = $this->get(route('post.edit', $post))
->assertOk()
->assertSee('Dashboard')
->assertSee('Title')
->assertSee('Slug')
->assertSee('Content')
->assertSee('Category')
->assertSee('Description')
->assertSee('Posted')
->assertSee('Send')
->assertSee($post->title)
->assertSee($post->content)
->assertSee($post->description)
->assertSee($post->slug)
->assertViewHas('categories', Category::pluck('id', 'title'))
->assertViewHas('post', $post);
$this->assertInstanceOf(Post::class, $response->viewData('post'));
$this->assertInstanceOf(Collection::class, $response->viewData('categories'));
}
public function test_edit_put(): void
{
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$data = [
'title' => 'Title',
'slug' => 'title',
'content' => 'Content',
'description' => 'Content',
'category_id' => 1,
'posted' => 'yes',
];
$this->put(route('post.update', $post), $data)
->assertRedirect(route('post.index'));
$this->assertDatabaseHas('posts', $data);
$this->assertDatabaseMissing('posts', $post->toArray());
}
public function test_edit_put_invalid(): void
{
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$this->get(route('post.edit', $post));
$data = [
'title' => 'a',
'slug' => '',
'content' => '',
'description' => '',
// 'category_id' => 1,
'posted' => '',
];
$this->put(route('post.update', $post), $data)
->assertRedirect(route('post.edit', $post))
->assertSessionHasErrors([
'title' => 'The title field must be at least 5 characters.',
'slug' => 'The slug field is required.',
'content' => 'The content field is required.',
'description' => 'The description field is required.',
'posted' => 'The posted field is required.',
'category_id' => 'The category id field is required.',
]);
}
public function test_edit_destroy(): void
{
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$data = [
'id' => $post->id,
];
$this->delete(route('post.destroy', $post))
->assertRedirect(route('post.index'));
$this->assertDatabaseMissing('posts', $data);
}
}And here are the exact same tests migrated to Pest:
<?php
use App\Models\Category;
use App\Models\Post;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
beforeEach(function () {
User::factory(1)->create();
$this->user = User::first();
$role = Role::firstOrCreate(['name' => 'Admin']);
Permission::firstOrCreate(['name' => 'editor.post.index']);
Permission::firstOrCreate(['name' => 'editor.post.create']);
Permission::firstOrCreate(['name' => 'editor.post.update']);
Permission::firstOrCreate(['name' => 'editor.post.destroy']);
$role->syncPermissions([1, 2, 3, 4]);
$this->user->assignRole($role);
$this->actingAs($this->user);
});
test('test index', function () {
Category::factory(3)->create();
User::factory(3)->create();
Post::factory(20)->create();
$response = $this->get(route('post.index'))
->assertOk()
->assertViewIs('dashboard.post.index')
->assertSee('Dashboard')
->assertSee('Create')
->assertSee('Show')
->assertSee('Delete')
->assertSee('Edit')
->assertSee('Id')
->assertSee('Title');
$this->assertInstanceOf(LengthAwarePaginator::class, $response->viewData('posts'));
});
test('test create get', function () {
Category::factory(10)->create();
$response = $this->get(route('post.create'))
->assertOk()
->assertSee('Dashboard')
->assertSee('Title')
->assertSee('Slug')
->assertSee('Content')
->assertSee('Category')
->assertSee('Description')
->assertSee('Posted')
->assertSee('Send')
->assertViewHas('categories', Category::pluck('id', 'title'))
->assertViewHas('post', new Post());
$this->assertInstanceOf(Post::class, $response->viewData('post'));
$this->assertInstanceOf(Collection::class, $response->viewData('categories'));
});
test('test create post', function () {
Category::factory(1)->create();
$data = [
'title' => 'Title',
'slug' => 'title',
'content' => 'Content',
'description' => 'Content',
'category_id' => 1,
'posted' => 'yes',
'user_id' => $this->user->id,
];
$this->post(route('post.store', $data))
->assertRedirect(route('post.index'));
$this->assertDatabaseHas('posts', $data);
});
test('test create post invalid', function () {
Category::factory(1)->create();
$data = [
'title' => '',
'slug' => '',
'content' => '',
'description' => '',
// 'category_id' => 1,
'posted' => '',
];
$this->post(route('post.store', $data))
->assertRedirect('/')
->assertSessionHasErrors([
'title' => 'The title field is required.',
'slug' => 'The slug field is required.',
'content' => 'The content field is required.',
'description' => 'The description field is required.',
'posted' => 'The posted field is required.',
'category_id' => 'The category id field is required.',
]);
});
test('test edit get', function () {
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$response = $this->get(route('post.edit', $post))
->assertOk()
->assertSee('Dashboard')
->assertSee('Title')
->assertSee('Slug')
->assertSee('Content')
->assertSee('Category')
->assertSee('Description')
->assertSee('Posted')
->assertSee('Send')
->assertSee($post->title)
->assertSee($post->content)
->assertSee($post->description)
->assertSee($post->slug)
->assertViewHas('categories', Category::pluck('id', 'title'))
->assertViewHas('post', $post);
$this->assertInstanceOf(Post::class, $response->viewData('post'));
$this->assertInstanceOf(Collection::class, $response->viewData('categories'));
});
test('test edit put', function () {
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$data = [
'title' => 'Title',
'slug' => 'title',
'content' => 'Content',
'description' => 'Content',
'category_id' => 1,
'posted' => 'yes',
];
$this->put(route('post.update', $post), $data)
->assertRedirect(route('post.index'));
$this->assertDatabaseHas('posts', $data);
$this->assertDatabaseMissing('posts', $post->toArray());
});
test('test edit put invalid', function () {
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$this->get(route('post.edit', $post));
$data = [
'title' => 'a',
'slug' => '',
'content' => '',
'description' => '',
// 'category_id' => 1,
'posted' => '',
];
$this->put(route('post.update', $post), $data)
->assertRedirect(route('post.edit', $post))
->assertSessionHasErrors([
'title' => 'The title field must be at least 5 characters.',
'slug' => 'The slug field is required.',
'content' => 'The content field is required.',
'description' => 'The description field is required.',
'posted' => 'The posted field is required.',
'category_id' => 'The category id field is required.',
]);
});
test('test destroy', function () {
User::factory(3)->create();
Category::factory(10)->create();
Post::factory(1)->create();
$post = Post::first();
$data = [
'id' => $post->id,
];
$this->delete(route('post.destroy', $post))
->assertRedirect(route('post.index'));
$this->assertDatabaseMissing('posts', $data);
});You can check out the rest of the full project tests in the official repository: https://github.com/libredesarrollo/book-course-laravel-base-11.
Testing an API with Token Authentication (Pest and PHPUnit)
When you need to test an API protected with Laravel Sanctum (from both PHPUnit and Pest), defining a global helper—for example in tests/Pest.php or in your test helper—is very handy for generating a valid token quickly:
function generateTokenAuth(): string
{
User::factory()->create();
return User::first()->createToken('myapptoken')->plainTextToken;
}From there, you can reuse generateTokenAuth() in any API test. For instance, to test an endpoint that returns all categories without pagination, we combine factory() to create the data, assertOk() to check status 200, and assertJson() to validate the JSON body:
test('test all', function () {
Category::factory(10)->create();
$categories = Category::get()->toArray();
$this->get(
'/api/category/all',
[
'Authorization' => 'Bearer ' . generateTokenAuth(),
]
)
->assertOk()
->assertJson($categories);
});Notice that we pass the Authorization header directly as the second argument of $this->get() (the HTTP headers array, just like you would with $this->getJson() in PHPUnit), without chaining extra calls like withHeaders().
On creation or update endpoints, it is also common to validate error messages in JSON or text responses. If you want to match a message using a flexible regular expression instead of an exact literal match, you can swap assertStringContainsString() for assertMatchesRegularExpression():
// Literal text match:
$this->assertStringContainsString('The title field is required.', $response->getContent());
// Regular expression match (modern equivalent of assertRegExp):
$this->assertMatchesRegularExpression('/The title field is required./', $response->getContent());Other checks using assertContent(), assertStatus(), or assertOk() stay identical for POST, PUT, and DELETE. As a final refactoring good practice, you can chain all assertions straight onto the request to avoid unnecessary intermediate $response variables and keep the file much cleaner.
🚀 Parallel Tests, Coverage, and Quality Tools in Laravel
As your test suite grows, execution time matters. If you have a test suite taking 8 seconds because each test runs a sleep(2) or multiple migrations, running them in parallel uses all your processor cores and cuts wait time dramatically:
$ php artisan test --parallelOr directly with Pest (which also works with PHPUnit thanks to the ParaTest integration Laravel includes out of the box):
$ vendor/bin/pest --parallelCode and Type Coverage
- Code Coverage (
--coverage): generates a console report showing what percentage of your code is covered by tests and which lines are still untested. You can even set a minimum threshold (for example,--min=40) so the suite fails in CI if someone pushes code that drops below that average. - Type Coverage (
--type-coverage): exclusive to Pest, it tells you what percentage of your application lacks explicit types on parameters, properties, and return values. Great for keeping quality standards high.
Laravel Pint: Effortless Code Style
Laravel Pint works "by magic" with no prior setup following Laravel's standard. But if you create a pint.json file at the root to customize PHP-CS-Fixer rules, you can automate high-impact habits:
- Strict types and final classes: tells Pint to add
declare(strict_types=1);at the top of every file and mark your classes asfinal. - Method ordering: prioritizes readability by placing private methods at the bottom of the class.
- Strict comparisons: automatically replaces loose comparisons (
==) with strict comparisons (===).
{
"rules": {
"declare_strict_types": true,
"final_class": true,
"strict_comparison": true
}
}⌨️ Peck PHP: Say Goodbye to Typos in Code
If you accidentally declare a property named naame (with a double e), Peck will catch it right away. Running vendor/bin/peck in your terminal scans class names, properties, methods, comments, and docblocks, pointing out the exact file and line of the typo.
PHPStan: "TypeScript" for PHP
PHPStan works as a static type analyzer for PHP (similar to what TypeScript does for JavaScript). It checks your code before running it and catches silent issues such as:
- Unreachable code: for example, a
returnstatement written afterdd()ordie(). - Return type mismatches: when a method promises to return an
intbut actually returns aViewinstance. - Unimported classes: warns you on the spot if you forgot to add a class's
usestatement.
public function index(): int
{
dd();
return view('dashboard.index');
}$ vendor/bin/phpstan🏗️ Rector PHP: Automated Refactoring
If PHPStan tells you what is wrong, Rector PHP fixes it for you automatically. It is ideal for modernizing legacy apps (for instance, moving from PHP 7 or earlier toward PHP 8.4) in seconds.
Among other things, Rector can automatically transform:
- Legacy
array()syntax into modern[]. - Verbose
switchstatements intomatchexpressions. - Removal of "dead code" (redundant variables or conditionals).
- Addition of missing return types.
public function index(): array
{
$result = array();
return $result;
}
public function user(User $user): User
{
if (true) {
$user = $user;
}
return $user;
}When running Rector:
$ vendor/bin/rectorWe get clean, modernized code:
public function index(): array
{
$result = [];
return $result;
}
public function user(User $user): User
{
return $user;
}🔌 Unit and Integration Testing in Laravel Livewire
In Livewire we can also write unit and integration tests following Laravel's same foundation. When working with PHPUnit classes, the file extends Tests\TestCase to access all HTTP helpers and the Livewire::test() helper.
tests/Feature/Blog/IndexTest.php:
<?php
namespace Tests\Feature\Blog;
use App\Livewire\Blog\Index;
use Livewire\Livewire;
use Tests\TestCase;
class IndexTest extends TestCase
{
public function test_index(): void
{
$this
->get(route('web.index'))
->assertSeeLivewire(Index::class)
->assertStatus(200)
->assertSee('Post List');
}
}Watch out for a detail that causes plenty of headaches at first! There are two classes named TestCase in a Laravel project:
- Wrong for HTTP/Feature tests:
PHPUnit\Framework\TestCase(comes from PHPUnit's pure core). - Right:
Tests\TestCase(your Laravel application's base class).
// use PHPUnit\Framework\TestCase;
use Tests\TestCase;If you import PHPUnit's class by accident, methods like $this->get() will not exist and the test will fail immediately. Tests\TestCase extends PHPUnit (and works whether you use PHPUnit or Pest), while adding the entire HTTP request, session, and assertion layer specific to Laravel.
Compared to other stacks like Inertia—where UI tests often lean more toward frontend testing with Vue—Livewire offers rich options for testing interactive components directly from the server side with Livewire::test(): checking whether a component rendered (assertSeeLivewire()), simulating form inputs, or checking whether elements and associated views load properly.
Pest with Livewire and AI Test Generation
If you have already taken my Laravel Base course, you know my philosophy: tests are not just window dressing. Their real value shows up when the app grows to dozens or hundreds of modules and you need to guarantee that a change at point A does not break point B.
Although I used PHPUnit in earlier courses and in my book, today I recommend using Pest with Livewire for its clean syntax via it() or test(). Also, AI is a fantastic ally for generating the initial skeleton of these tests, as long as you audit the output: sometimes it misses Pest conventions or mixes up imports.
In a Livewire test with Pest, you should check at least four things:
- Rendering: Does the page or component load the expected content? (
assertSee()) - Authentication and permissions: Does the component block unauthorized users? (
actingAs($user),assertForbidden()) - Reactive properties: Are values assigned properly? (
set('title', '...')) - Validation and actions: Does it fail when data is missing or invalid? (
call('save'),assertHasErrors())
it('renders the blog show page with post', function () {
$post = Post::factory()->create();
Livewire::test('pages::blog.show', ['post' => $post])
->assertSee($post->title);
});
test('team invitations cannot be created by members', function () {
$owner = User::factory()->create();
$member = User::factory()->create();
$team = Team::factory()->create();
$team->members()->attach($owner, ['role' => TeamRole::Owner->value]);
$team->members()->attach($member, ['role' => TeamRole::Member->value]);
$this->actingAs($member);
Livewire::test('pages::teams.invite-member-modal', ['team' => $team])
->set('inviteEmail', 'invited@example.com')
->set('inviteRole', TeamRole::Member->value)
->call('createInvitation')
->assertForbidden();
});To generate starter tests quickly in projects with the Pest plugin, you can run:
$ php artisan pest:test pages/blog/indexTestOr specify the Feature folder with --feature (or use php artisan make:test --pest):
$ php artisan pest:test pages/blog/indexTest --featureTests are an essential safety net; in day-to-day professional work the depth depends on team standards, but with this you already have a solid foundation.
First Steps Testing the Blog Module in Livewire
Before writing new tests in any module, run php artisan test to confirm the entire current suite passes with no errors. If anything fails right out of the gate, fix it before moving forward.
To start without getting bogged down in filters from minute one, let us first validate basic access to the blog listing in tests/Feature/Blog/IndexTest.php.
Practical tip: before enabling
RefreshDatabasefor the first time, back up or copy your local.sqlitefile in case you forgot to configure the isolated environment inphpunit.xml.
The first step is identifying the exact route to test (for example, /blog). If you point to a nonexistent route you will get a 404; if you expected a 200 and get a 404, you will know right away that the issue is in your route definitions:
<?php
namespace Tests\Feature\Blog;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class IndexTest extends TestCase
{
public function test_example(): void
{
// GET request to /blog
$response = $this->get('/blog');
$response->assertStatus(200);
}
}Remember this is a Feature test rather than a Unit test because we are evaluating the full blog module—including routing, middleware, Livewire components, and HTTP response—not an isolated math function.
Named Routes and Specific Assertions in Livewire
One key tip is using named routes via the route() helper instead of hardcoded URLs. If you decide tomorrow to change the URL from /blog to /bloquecito, your tests will keep passing because they point to the route name web.index:
public function test_index(): void
{
$this->get(route('web.index'))
->assertOk();
}If you used $this->get('blog') as a static path, any URL change would break every test with a 404 error, forcing you to edit file after file.
✅ Evaluating Views, Status 200, and Data with Livewire::test()
When testing standard routes with TestCase, we typically start by checking status 200 with assertOk() or assertStatus(200) and verifying the loaded view through assertViewIs():
public function test_index_view(): void
{
$response = $this->get(route('web.index'));
$response->assertStatus(200);
// Validate that the view is the expected one
$response->assertViewIs('web.index');
}The best part is that Laravel saves us from parsing HTML manually: its assertions also check redirects, visible content, or whether a user is authenticated and authorized.
Now, when content lives inside a full-page or embedded Livewire component, we use Livewire::test(Index::class) to chain assertions directly on the component (such as assertSee(), assertViewHas(), and assertViewIs()):
<?php
namespace Tests\Feature\Blog;
use App\Livewire\Blog\Index;
use App\Models\Post;
use Livewire\Livewire;
use Tests\TestCase;
class IndexTest extends TestCase
{
public function test_index(): void
{
$this->get(route('web.index'))
->assertOk()
->assertSeeLivewire(Index::class);
Livewire::test(Index::class)
->assertSee('Post List')
->assertViewHas('posts', Post::with('category')
->where('posted', 'yes')
->paginate(15))
->assertViewIs('livewire.blog.index');
}
}Need to inspect the exact collection reaching the component when an assertion fails? You can pass a callback to assertViewHas() and use dump() or dd() to debug data in the console:
->assertViewHas('posts', function ($posts) {
dump(Post::paginate(15));
dd($posts);
})Keep a practical detail in mind: if you call dd() on the entire HTML response, the output is often so long that the terminal truncates it. Using a callback inside assertViewHas()—and calling dump() before dd() if you want to inspect two variables at once—is much easier for comparing exact data.
⚡ Integration Testing in Laravel with Inertia and Vue
In Inertia and Vue projects, we will not write tests in the exact same order we built the app—instead, we start with the simplest modules, such as the blog listing, to master the mechanics before moving on to more complex flows.
Automated Tests with AI (Laravel Boost and Pest)
Here is where Artificial Intelligence truly shines: when working on existing code. Unlike asking it to "invent" a module from scratch, generating tests against controllers you already wrote makes AI hallucination rare; it simply reads your actual code and suggests test cases to evaluate it. That cuts time spent way down, because let us be honest: writing dozens of repetitive tests by hand can get tedious.
Instead of asking for "all the tests for the project," working module by module with clear context works much better:
- Context: pass the exact file to test, for example
app/Http/Controllers/Blog/PostController.php. - Execution: it will generate a test in
tests/Feature/Blog/PostControllerTest.phpfollowing Pest and Laravel conventions. - Verification: it will cover the paginated listing of 15 records in
index, the200and404cases inshow, and search filters.
Suggested prompt: "Write the tests for the module in
app/Http/Controllers/Blog/PostController.phpusing Pest and Laravel best practices."
Then run that specific file with:
$ php artisan test --compact tests/Feature/Blog/PostControllerTest.phpIf any test fails, iterate without hesitation: tell AI what structure the controller actually returned so it adjusts the assertion.
From Traditional Laravel to Inertia: The Vite Error and assertViewIs('app')
Whether you write your tests with PHPUnit or Pest (remember their assertion methods have an almost one-to-one mapping), let us see what happens when we try to test an Inertia route as if it returned a traditional Blade view.
We create the test in tests/Feature/Blog/PostTest.php with php artisan make:test Blog/PostTest:
<?php
namespace Tests\Feature\Blog;
// use PHPUnit\Framework\TestCase;
use Tests\TestCase;
class PostTest extends TestCase
{
public function test_index(): void
{
$this->get(route('web.index'))
->assertViewIs('blog.show')
->assertStatus(200);
}
}Running php artisan test will likely hit this error first:
Unable to locate file in Vite manifest: resources/js/Pages/Blog/Index.vue. (View: C:\Users\andre\Herd\inertiastore\resources\views\app.blade.php)This means Vite has not generated its build manifest yet. You have two quick fixes: start the dev server with npm run dev or compile production assets with npm run build.
Once assets are compiled, running the tests again shows a second error:
+++ Actual
@@ @@
-'blog.show'
+'app'Why does this happen? Because assertViewIs() checks the root Blade view, not the Vue component. Under the hood, when a controller returns an inertia() response, Laravel always loads the container template app.blade.php (that is, app). Doing ->assertViewIs('app') would clear the error, but it makes little sense because it does not verify which Vue component mounted or which props it received. That is what native Inertia assertions are for.
Using assertInertia(), has(), and where()
To evaluate Inertia responses, we import Inertia\Testing\AssertableInertia as Assert. Before writing final assertions, a great trick to explore what the page receives is calling dd($page) inside assertInertia():
<?php
namespace Tests\Feature\Blog;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class PostTest extends TestCase
{
public function test_index(): void
{
$this->get(route('web.index'))
->assertInertia(fn (Assert $page) => dd($page));
}
}Running the test prints the full AssertableInertia object in the console (the test equivalent of the global {{ $page }} object you consume inside resources/js/Pages/Blog/Index.vue), including shared props (auth, jetstream, flash, errors) and controller-specific data (posts, categories, filters, etc.):
Inertia\Testing\AssertableInertia {#2397
-props: array:14 [
"errors" => []
"jetstream" => array:11 [
"canCreateTeams" => false
"canManageTwoFactorAuthentication" => true
"canUpdatePassword" => true
"canUpdateProfileInformation" => true
"hasEmailVerification" => false
"flash" => []
"hasAccountDeletionFeatures" => true
"hasApiFeatures" => true
"hasTeamFeatures" => true
"hasTermsAndPrivacyPolicyFeature" => true
"managesProfilePhotos" => true
]
"auth" => array:1 [
"user" => null
]
"errorBags" => []
"flash" => array:1 [
"message" => null
]
"step" => 1
"cart" => []
"posts" => array:13 [
"current_page" => 1
"data" => array:15 [
0 => array:13 [
"id" => 2
"title" => "Post 5111"
"slug" => "post-4"
"date" => "2024-08-22"
"image" => "1729333215.png"
"text" => "asasasasas"
"description" => "asasasas"
"posted" => "not"
"type" => "course"
"category_id" => 2
"created_at" => "2024-08-18T09:54:24.000000Z"
"updated_at" => "2024-09-21T09:43:12.000000Z"
"category" => array:7 [
"id" => 2
"title" => "Cate 2"
"slug" => "cate-2"
"image" => null
"text" => null
"created_at" => "2024-08-15T10:08:19.000000Z"
"updated_at" => "2024-08-15T10:08:19.000000Z"
]
]
]
"first_page_url" => "http://inertiastore.test/blog?page=1"
"from" => 1
"last_page" => 47
"last_page_url" => "http://inertiastore.test/blog?page=47"
"links" => array:15 [
0 => array:3 [
"url" => null
"label" => "« Previous"
"active" => false
]
]
"next_page_url" => "http://inertiastore.test/blog?page=2"
"path" => "http://inertiastore.test/blog"
"per_page" => 15
"prev_page_url" => null
"to" => 15
"total" => 702
]
"categories" => array:2 [
0 => array:7 [
"id" => 1
"title" => "Cate 1"
"slug" => "category-1"
"image" => null
"text" => null
"created_at" => "2024-08-15T10:08:12.000000Z"
"updated_at" => "2024-08-15T10:08:12.000000Z"
]
1 => array:7 [
"id" => 2
"title" => "Cate 2"
"slug" => "cate-2"
"image" => null
"text" => null
"created_at" => "2024-08-15T10:08:19.000000Z"
"updated_at" => "2024-08-15T10:08:19.000000Z"
]
]
"prop_type" => null
"prop_category_id" => null
"prop_from" => null
"prop_to" => null
"prop_search" => null
]
-path: null
#interacted: []
-component: "Blog/Index"
-url: "/blog"
-version: "b05311e78830e9fb34e382b9802ceab2"
}(The output above was trimmed to keep the guide concise, though I recommend running it in your environment to inspect your own data.)
If you want to inspect only a single complex prop, such as the posts paginator, you can isolate it by passing a callback to has(). You can even rename the closure parameter to $posts to make the code clearer:
$this->get(route('web.index'))
->assertInertia(fn (Assert $page) => $page
->component('Blog/Index')
->has('posts', fn (Assert $posts) => dd($posts)));That displays only the internal structure of posts (current_page, data, last_page, total, and so on):
Inertia\Testing\AssertableInertia {#2305
-props: array:13 [
"current_page" => 1
"data" => array:15 [
...
14 => array:13 [
"id" => 18
"title" => "NSf"
"slug" => "nsf"
"date" => "2023-11-07 00:00:00"
"image" => null
"text" => "..."
"description" => null
"posted" => "yes"
"type" => "movie"
"category_id" => 2
"created_at" => "2024-09-21T09:43:12.000000Z"
"updated_at" => "2024-09-21T09:43:12.000000Z"
"category" => array:7 [
"id" => 2
"title" => "Cate 2"
"slug" => "cate-2"
"image" => null
"text" => null
"created_at" => "2024-08-15T10:08:19.000000Z"
"updated_at" => "2024-08-15T10:08:19.000000Z"
]
]
]
"first_page_url" => "http://inertiastore.test/blog?page=1"
"from" => 1
"last_page" => 47
"last_page_url" => "http://inertiastore.test/blog?page=47"
"links" => array:15 [
...
14 => array:3 [
"url" => "http://inertiastore.test/blog?page=2"
"label" => "Next »"
"active" => false
]
]
"next_page_url" => "http://inertiastore.test/blog?page=2"
"path" => "http://inertiastore.test/blog"
"per_page" => 15
"prev_page_url" => null
"to" => 15
"total" => 702
]
}Combining component(), has(), and where()
In resources/js/Pages/Blog/Index.vue, our component declares these props:
props: {
posts: Object,
categories: Array,
prop_category_id: String,
prop_type: String,
prop_from: String,
prop_to: String,
prop_search: String,
},And in app/Http/Controllers/Blog/PostController.php, we have a query with conditional when() filters, a with('category') relation, and 15-item pagination:
$posts = Post::when(...)
->with('category')
->paginate(15);If we are not passing filters in the test, we can compare directly against Post::with('category')->paginate(15). To validate all of this, we have three core methods on AssertableInertia (see the full reference at https://inertiajs.com/testing):
component('Blog/Index'): confirms the exact name of the rendered Vue component.has('prop_from')orhas('posts.data', 15): verifies that a prop exists and, if you pass a second numeric argument, validates how many items it holds.where('key', $value): checks exact values (for example, verifying thatprop_fromisnullor thatcategories.0.titleis'Cate 1'using dot notation).
$this->get(route('web.index'))
->assertOk()
->assertInertia(fn (Assert $page) => $page
->component('Blog/Index')
->where('categories', Category::get())
->where('prop_from', null)
->where('posts', Post::with('category')->paginate(15))
->has('prop_from')
->has('categories.0.title')
->where('categories.0.title', 'Cate 1')
->has('posts', fn (Assert $posts) => $posts
->where('last_page', 47)
->has('data', 15)
->etc()
)
);Note on Testing Library vs. Laravel tests: if you come from the JavaScript world, you might wonder whether to use Testing Library (with Vitest or Jest) instead of Laravel tests. In practice they play complementary roles: Laravel tests (assertInertia(), Livewire::test()) quickly validate backend behavior, permissions, the database, and the props contract your view receives, whereas Testing Library focuses on testing complex UI interactions and DOM events in isolation inside your Vue or React components.
🧭 Best Practices and Benefits of Automated Testing
- Name each test after the behavior it validates (for example,
test('guests cannot create posts', ...)). - Avoid dependencies between tests: every test should run independently and in any order.
- Keep the database clean with
RefreshDatabaseand generate fresh data using factories. - Check the status code first (
assertOk()orassertStatus(200)): if the route fails with a404or500, the remaining assertions lose meaning. - Trigger an intentional failure from time to time during development to confirm your test is actually checking what you think it checks.
- Integrate running
php artisan testinto your CI/CD pipeline (such as GitHub Actions) to validate every commit or pull request automatically.
In the end, building this habit brings immediate benefits: you catch bugs before they reach production, refactor without fear of breaking older modules, raise overall project quality, and lay the groundwork for applying TDD (Test-Driven Development) in your projects.
🧾 Conclusion
Laravel puts testing within reach of every developer from minute one. Both PHPUnit and Pest let you build solid suites for traditional routes, Sanctum APIs, Livewire components, and Inertia + Vue apps—the difference being that Pest lightens the syntax without giving up any of PHPUnit's power.
Run your tests after every major change, lean on dd() or dump() when you need to inspect responses, and automate the suite in your workflow. Your application—and your peace of mind when deploying—will thank you.
❓ Frequently Asked Questions
What is PHPUnit and what is it used for in Laravel?
PHPUnit is the most widely used testing framework in PHP and comes built into Laravel by default. It is used to write unit and integration tests that automatically verify your routes, controllers, models, permissions, and responses work properly after every change.
What is the difference between PHPUnit and Pest?
Pest (pestphp) uses a much cleaner, more minimalist functional syntax based on test(), it(), and beforeEach(), whereas PHPUnit uses classes with extends TestCase and methods like setUp(). Under the hood Pest runs on PHPUnit, so both share the same power and Laravel compatibility.
How do you configure tests/Pest.php and the testing database?
In tests/Pest.php you can apply traits globally, for example uses(TestCase::class, RefreshDatabase::class)->in('Feature');. I also recommend enabling DB_CONNECTION=sqlite and DB_DATABASE=:memory: in phpunit.xml so tests run in memory without touching your development database.
How do you implement authentication in web and API tests?
For web, Livewire, or Inertia routes, just use $this->actingAs($user) before sending the request. For token-protected APIs (such as Laravel Sanctum), you can create a helper like generateTokenAuth() and pass it in the Authorization: Bearer ... header inside $this->get() or $this->getJson().
How do you test views and props in Livewire and Inertia?
In traditional Blade views and Livewire, you can use assertViewIs(), assertViewHas(), assertSee(), and Livewire::test(). In Inertia with Vue or React, use assertInertia() along with component(), has(), and where() to validate both the loaded component and its props.
Is it worth applying TDD in Laravel?
Yes. Writing tests first forces you to design more decoupled, predictable, and verifiable code from the start, while also serving as a clear specification if you use AI tools to speed up implementation.