Snapshot Testing

Snapshot Testing is a great way to test your code by comparing by the given expectation value to a previously stored snapshot of the same value. This is useful when you want to ensure that your code is not changing its output unexpectedly.

As example, let's say you have a string response coming from an API. You can use snapshot testing to ensure that the response is not changing unexpectedly.

1it('has a contact page', function () {
2 $response = $this->get('/contact');
3 
4 expect($response)->toMatchSnapshot();
5});

The first time you run this test, it will create a snapshot file - at tests/.pest/snapshots - with the response content. The next time you run the test, it will compare the response with the snapshot file. If the response is different, the test will fail. If the response is the same, the test will pass.

In addition, the given expectation value doesn't have to be a response; it can be anything. For example, you can snapshot an array:

1$array = /** Fetch array somewhere */;
2 
3expect($array)->toMatchSnapshot();

And of course, you can "rebuild" the snapshots at any time by using the --update-snapshots option:

1./vendor/bin/pest --update-snapshots

Handling Dynamic Data

Sometimes, the expected value may contain dynamic data that you cannot control, such as CSRF tokens in a form. In those cases, you can use Expectation Pipes to replace that data. Here is an example:

1expect()->pipe('toMatchSnapshot', function (Closure $next) {
2 if (is_string($this->value)) {
3 $this->value = preg_replace(
4 '/name="_token" value=".*"/',
5 'name="_token" value="my_test"',
6 $this->value
7 );
8 }
9 
10 return $next();
11});

In this chapter, we've seen how powerful snapshot testing is. In the following chapter, we will dive into Pest's custom helpers: Custom Helpers