Testing with Pest

Pest is a PHP testing framework built on top of PHPUnit. In Pest, you write a test as it('description', function () { ... }) or test(...), with no class, and…

One small check in PHPUnit needs a class, a method, then $this->assertSame(3, add(1, 2)). In Pest, expect(add(1, 2))->toBe(3) inside it('adds', ...) is enough. The test result is the same, with far less typing.

Pest is a PHP testing framework built on top of PHPUnit. The difference is in how you write tests. Pest uses no class and no methods. You only need the functions it() or test(), which read like sentences, and expect(), whose checks (such as toBe()) can be chained, much like in Vitest. What runs the tests is still PHPUnit, behind the scenes. Picture two recipes for the same dish. One is written as a form full of columns, the other as an ordinary sentence: "make sure the rice is fluffy". The dish is the same, only the writing differs. In this picture, the form is PHPUnit, the sentence is Pest, and the dish is the test that runs.

A first test with Pest

Take one file, tests/Unit/MathTest.php. To keep it short, the functions under test sit at the top (in a real project, they live in the app folder):

<?php

function add($a, $b)
{
    return $a + $b;
}

function double($n)
{
    return $n * 2;
}

it('can add numbers', function () {
    expect(add(1, 2))->toBe(3);
});

Running it: ./vendor/bin/pest

Run the tests with ./vendor/bin/pest:

   PASS  Tests\Unit\MathTest
  ✓ it can add numbers

  Tests:    1 passed (1 assertions)
  Duration: 0.05s

One line per test: ✓ passed, ⨯ failed. In Laravel, php artisan test prints the same format. When something fails, a FAILED block appears under the list. That block holds the test's name, its message, and a piece of the code with an arrow ➜ on the failing line.

expect() and its checks

Watch the types. expect(add(1, 2))->toBe('3') fails, because toBe compares with ===, and the int 3 (a whole number) is not the text '3':

   FAIL  Tests\Unit\MathTest
  ⨯ it can add numbers
  ────────────────────────────────────────────────────────────────────────────
   FAILED  Tests\Unit\MathTest > it can add numbers
  Failed asserting that 3 is identical to '3'.

  at tests/Unit/MathTest.php:14
     10▕     return $n * 2;
     11▕ }
     12▕
     13▕ it('can add numbers', function () {
  ➜  14▕     expect(add(1, 2))->toBe('3');
     15▕ });

  1   tests/Unit/MathTest.php:14


  Tests:    1 failed (1 assertions)
  Duration: 0.06s

toEqual('3') passes, because toEqual compares loosely (==). The checks you'll use most:

Check Passes when
toBe(3) exactly the same, type included (===)
toEqual('3') the same after a loose comparison (==)
toBeTrue() / toBeFalse() exactly true / false
toBeGreaterThan(5) bigger than 5
toContain('a') the array (or text) contains 'a'
toBeEmpty() empty, for example [] or ''
toHaveCount(3) it holds 3 items

Checks can be chained, and not flips the check after it:

expect($name)->toBeString()->not->toBeEmpty();

expect($user)->toBeObject()
    ->and($user->name)->toBe('Budi');

Dataset: one test, many data

A dataset is a list of data for one test, like a data provider in PHPUnit. In Pest, you attach a dataset with ->with([...]):

it('doubles a number', function (int $input, int $expected) {
    expect(double($input))->toBe($expected);
})->with([
    [1, 2],
    [5, 10],
    [0, 0],
]);

Why more than one row? Imagine double wrongly written as return $n + 2;. With a single row [2, 4], the test still passes, because by chance 2 + 2 = 2 × 2. The rows [1, 2] and [5, 10] fail at once, so the bug is found.

describe(): grouping tests

describe() groups the tests about one thing, just as in Vitest:

describe('Calculator', function () {
    it('adds two numbers', function () {
        expect(add(2, 3))->toBe(5);
    });
});

The group's name is printed in front of the test's name: `Calculator` → it adds two numbers.

From PHPUnit to Pest

The same test, written with PHPUnit and then with Pest:

// PHPUnit
class MathTest extends TestCase
{
    public function test_add(): void
    {
        $this->assertSame(3, add(1, 2));
    }
}

// Pest
it('adds', function () {
    expect(add(1, 2))->toBe(3);
});

Pest runs on top of PHPUnit. So PHPUnit files and Pest files can be used side by side in one project, and you can switch to Pest a little at a time. Inside a Pest test, $this->assertSame(...) still works too.

In the exercises: imitate expect() yourself

The exercise sandbox runs plain PHP without Pest. So you build expect() yourself: a function that returns an array of check functions. Each check carries the value given to expect(), through use ($value):

function expect($value): array
{
    return [
        'toBe' => function ($expected) use ($value) {
            return $value === $expected;
        },
    ];
}

echo "toBe: " . (expect(5)['toBe'](5) ? 'PASS' : 'FAIL') . "\n";   // toBe: PASS

⚠️ Where Pest tests slip

TL;DR: Pest is a PHP testing framework built on top of PHPUnit. In Pest, you write a test as it('description', function () { ... }) or test(...), with no class, and you check the result with expect($value)->toBe($expected), much like Vitest. toBe compares strictly (===), toEqual loosely (==). Checks such as toBe can be chained, not flips the check after it, and ->and($other) switches to another value. ->with([[1, 2], [5, 10]]) attaches a dataset (a list of data for one test), so the test runs once for every row of data. Every row is printed as a test of its own, for example it doubles a number with (1, 2). Pest runs with ./vendor/bin/pest. In the exercise sandbox, expect() is imitated with an array of functions that use use ($value), the way a PHP function with no name brings in a variable from outside.

⚡ A first test with Pest

Write:

it('can add numbers', function () {
    expect(add(1, 2))->toBe(3);
});

Meaning: Pest is a PHP testing framework built on top of PHPUnit. No class, no method: it() is one test, as in Vitest. The value being checked goes into expect(), and the value you expect goes into toBe(). Far less typing, yet PHPUnit still runs the test behind the scenes.

⚡ toBe or toEqual

Guess first: add(1, 2) returns the int 3. Does expect(add(1, 2))->toBe('3'), with the text '3', pass or fail?

It fails. toBe compares with ===, and the int 3 is not the text '3'. toEqual('3') passes, because toEqual compares loosely (==).

Meaning: When the type matters, use toBe.

⚡ Dataset: one test, many data

Write:

it('doubles a number', function (int $input, int $expected) {
    expect(double($input))->toBe($expected);
})->with([
    [1, 2],
    [5, 10],
    [0, 0],
]);

Meaning: A dataset is a list of data for one test. ->with([...]) runs the test once for every row: the row's values become $input and $expected, and every row is printed as a test of its own. double multiplies a number by 2. Use several rows, because one row can match by chance even when the code is wrong.

What you will learn