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);
});
it('can add numbers', function () { ... }): one test, likeitin Vitest. The first text is its description, and the second argument is a function with no name that holds the test. Pest prints the description with the prefixit, so it reads "it can add numbers".test('adds two numbers', function () { ... })is exactly the same, just without theitprefix. Pick whichever reads better as a sentence.expect(add(1, 2))->toBe(3): the value being checked goes intoexpect(), and the value you expect goes into the checktoBe(). Pest calls a check liketoBe()an expectation, the same thing as a matcher in Vitest.- No
class, no$this->assert.... Pest wraps that function into a PHPUnit test by itself.
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');
toBeString()checks that the value is a string,toBeObject()that it is an object, and->not->toBeEmpty()means "must not be empty".->and($otherValue)starts a new check for another value in the same chain. The value goes inside the parentheses, here$user->name(the propertynameof the object$user).
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],
]);
->with([...])runs the test once for every row. Each row is one case, and its values become the function's arguments:$input, then$expected.- Pest prints each row as a test of its own:
✓ it doubles a number with (1, 2),✓ it doubles a number with (5, 10),✓ it doubles a number with (0, 0). - A named row,
'five' => [5, 10], is printed aswith dataset "five". - A dataset many files use can be registered once with
dataset('numbers', [...]), then used with->with('numbers').
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
- In PHP, a function with no name can't read variables from outside by itself.
use ($value)carries$valueinto the check function. expect(5)['toBe']takes the checktoBeout of the array, then(5)calls it. Soexpect(5)['toBe'](5)compares 5 with 5.- For
toContain, usein_array($item, $value), which checks whether$itemis in the array. FortoBeEmpty,count($value) === 0. - The
it()style can be imitated with a function that prints"it " . $name . ": "and thenPASSorFAILfrom the result of its check. A dataset is imitated with an array of rows andforeach.
⚠️ Where Pest tests slip
- Using
toBeas if it weretoEqual.toBeuses===:3and'3'differ, and so do5and5.0. - A dataset with one row that happens to match. A bug can pass unnoticed. Add several rows, including edge cases like
0. - The number of arguments doesn't match the row. The row
[1, 2]needs a function with two parameters,function (int $input, int $expected). - Printing PASS without comparing anything. In the sandbox,
PASSmust come from the result of===, not from text that's always the same.
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.