0
0
LaravelHow-ToBeginner · 3 min read

How to Use Pest in Laravel for Simple Testing

To use Pest in Laravel, first install it via Composer with composer require pestphp/pest --dev. Then run ./vendor/bin/pest --init to set up Pest, and write tests in the tests/Feature or tests/Unit folders using Pest's simple syntax.
📐

Syntax

Pest uses a clean and simple syntax for writing tests. You define tests with the test function or the global it function. Each test has a description and a callback function where you write assertions.

  • test('description', function () { ... }): Defines a test with a description.
  • it('does something', function () { ... }): Alias for test, reads like a sentence.
  • Use Laravel's $this->get() or other helpers inside the callback.
  • Assertions like ->assertStatus(200) check results.
php
test('home page loads', function () {
    $response = $this->get('/');
    $response->assertStatus(200);
});
💻

Example

This example shows a simple feature test using Pest in Laravel. It checks that the home page returns a 200 status code.

php
<?php

use function Pest\Laravel\get;

test('home page returns status 200', function () {
    $response = get('/');
    $response->assertStatus(200);
});
Output
PASS Tests\Feature\HomePageTest ✓ home page returns status 200 Tests: 1 passed Time: 0.12s
⚠️

Common Pitfalls

Common mistakes when using Pest in Laravel include:

  • Not installing Pest with --dev flag, so it’s missing in production.
  • Forgetting to run ./vendor/bin/pest --init to set up Pest files.
  • Using PHPUnit syntax instead of Pest’s simpler functions.
  • Not importing Pest helper functions like test or it.
php
<?php
// Wrong: Using PHPUnit style in Pest file
public function test_example()
{
    $this->assertTrue(true);
}

// Right: Using Pest style
it('checks true is true', function () {
    expect(true)->toBeTrue();
});
📊

Quick Reference

CommandDescription
composer require pestphp/pest --devInstall Pest in Laravel project
./vendor/bin/pest --initInitialize Pest configuration and test files
test('desc', function () { ... })Define a test with description
it('does something', function () { ... })Alias for test, reads like a sentence
expect($value)->toBe($expected)Make assertions in Pest style

Key Takeaways

Install Pest in Laravel using Composer with the --dev flag.
Initialize Pest with ./vendor/bin/pest --init before writing tests.
Write tests using simple functions like test() or it() with clear descriptions.
Use Pest's expect() for readable assertions instead of PHPUnit methods.
Avoid mixing PHPUnit syntax with Pest to keep tests clean and simple.