How to setup Pest with Laravel

Pest is an alternative way of writing unit tests which in my opinion makes writing and reading tests simple and easy.

I will certainly be using it as the default method for writing unit tests in Laravel projects.

How to setup

Open up the terminal application and change the current directory to the Laravel project you want to install Pest.

Run the following to install Pest.

composer remove phpunit/phpunit
composer require pestphp/pest --dev --with-all-dependencies

When running the command the following prompt appears, select the default yes as phpunit will be reinstalled.

Do you want to remove it from require-dev [yes]?

Run the pest command to verify that it’s working.

./vendor/bin/pest 

Also the artisan test command can be used.

php artisan test

Example Pest Test

This is a simple test to show how to write pest tests.

Create a file called PestTest.php inside of the tests/Unit folder and add the following content

<?php

it('pest test', function () {
   $result = true;
 
   expect($result)->toBeTrue();
});

Now run the tests.

php artisan test --filter="PestTest"

You will see it is passed and the $result variable matches the expectation.

Change the expect line to the following.

expect($result)->toBeFalse();

Re-run the test.

php artisan test --filter="PestTest"

As the $result doesn’t match the expectation the test will show as failed.

Use the expectations page to see all the checks you can make against data from your PHP methods.