Skip to content

Commit d9394b9

Browse files
Initial Commit
0 parents  commit d9394b9

16 files changed

+1170
-0
lines changed

README.md

+310
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,310 @@
1+
2+
# Snapshot testing with PHPUnit
3+
> Snapshot testing is a way to test without writing actual test cases
4+
5+
```php
6+
use Spatie\Snapshots\MatchesSnapshots;
7+
8+
class OrderTest
9+
{
10+
use MatchesSnapshots;
11+
12+
public function test_it_casts_to_json()
13+
{
14+
$order = new Order(1);
15+
16+
$this->assertMatchesJsonSnapshot($order->toJson());
17+
}
18+
}
19+
```
20+
21+
On the first run, the test runner will create a new snapshot.
22+
23+
```
24+
> ./vendor/bin/phpunit
25+
26+
There was 1 incomplete test:
27+
28+
1) OrderTest::test_it_casts_to_json
29+
Snapshot created for OrderTest__test_it_casts_to_json__1
30+
31+
OK, but incomplete, skipped, or risky tests!
32+
Tests: 1, Assertions: 0, Incomplete: 1.
33+
```
34+
35+
On subsequent runs, the test will pass as long as the snapshot doesn't change.
36+
37+
```
38+
> ./vendor/bin/phpunit
39+
40+
OK (1 test, 1 assertion)
41+
```
42+
43+
If there's a regression, the test will fail!
44+
45+
```php
46+
$orderId = new Order(2); // Regression! Was `1`
47+
```
48+
```
49+
> ./vendor/bin/phpunit
50+
51+
1) OrderTest::test_it_casts_to_json
52+
Failed asserting that two strings are equal.
53+
--- Expected
54+
+++ Actual
55+
@@ @@
56+
Failed asserting that '{"id":2}' matches JSON string "{
57+
"id": 1
58+
}
59+
60+
FAILURES!
61+
Tests: 1, Assertions: 1, Failures: 1.
62+
```
63+
## Installation
64+
65+
You can install the package via composer:
66+
67+
```bash
68+
composer require --dev spatie/phpunit-snapshot-assertions
69+
```
70+
71+
## Usage
72+
73+
To make snapshot assertions, use the `Spatie\Snapshots\MatchesSnapshots` trait in your test case class. This adds a set of assertion methods to the class:
74+
75+
- `assertMatchesSnapshot($actual)`
76+
- `assertMatchesFileHashSnapshot($actual)`
77+
- `assertMatchesFileSnapshot($actual)`
78+
- `assertMatchesHtmlSnapshot($actual)`
79+
- `assertMatchesJsonSnapshot($actual)`
80+
- `assertMatchesObjectSnapshot($actual)`
81+
- `assertMatchesTextSnapshot($actual)`
82+
- `assertMatchesXmlSnapshot($actual)`
83+
- `assertMatchesYamlSnapshot($actual)`
84+
85+
### Snapshot Testing 101
86+
87+
Let's do a snapshot assertion for a simple string, "foo".
88+
89+
```php
90+
public function test_it_is_foo() {
91+
$this->assertMatchesSnapshot('foo');
92+
}
93+
```
94+
95+
The first time the assertion runs, it doesn't have a snapshot to compare the string with. The test runner generates a new snapshot and marks the test as incomplete.
96+
97+
```
98+
> ./vendor/bin/phpunit
99+
100+
There was 1 incomplete test:
101+
102+
1) ExampleTest::test_it_matches_a_string
103+
Snapshot created for ExampleTest__test_it_matches_a_string__1
104+
105+
OK, but incomplete, skipped, or risky tests!
106+
Tests: 1, Assertions: 0, Incomplete: 1.
107+
```
108+
109+
Snapshot ids are generated based on the test and testcase's names. Basic snapshots return a plain text or YAML representation of the actual value.
110+
111+
```txt
112+
foo
113+
```
114+
115+
Let's rerun the test. The test runner will see that there's already a snapshot for the assertion and do a comparison.
116+
117+
```
118+
> ./vendor/bin/phpunit
119+
120+
OK (1 test, 1 assertion)
121+
```
122+
123+
If we change actual value to "bar", the test will fail because the snapshot still returns "foo".
124+
125+
```php
126+
public function test_it_is_foo() {
127+
$this->assertMatchesSnapshot('bar');
128+
}
129+
```
130+
```
131+
> ./vendor/bin/phpunit
132+
133+
1) ExampleTest::test_it_matches_a_string
134+
Failed asserting that two strings are equal.
135+
--- Expected
136+
+++ Actual
137+
@@ @@
138+
-'foo'
139+
+'bar'
140+
141+
FAILURES!
142+
Tests: 1, Assertions: 1, Failures: 1.
143+
```
144+
145+
When we expect a changed value, we need to tell the test runner to update the existing snapshots instead of failing the test. This is possible by adding a`-d --update-snapshots` flag to the `phpunit` command, or setting the `UPDATE_SNAPSHOTS` env var to `true`.
146+
147+
```
148+
> ./vendor/bin/phpunit -d --update-snapshots
149+
150+
OK (1 test, 1 assertion)
151+
```
152+
153+
As a result, our snapshot file returns "bar" instead of "foo".
154+
155+
```txt
156+
bar
157+
```
158+
159+
### File snapshots
160+
161+
The `MatchesSnapshots` trait offers two ways to assert that a file is identical to the snapshot that was made the first time the test was run:
162+
163+
The `assertMatchesFileHashSnapshot($filePath)` assertion asserts that the hash of the file passed into the function and the hash saved in the snapshot match. This assertion is fast and uses very little disk space. The downside of this assertion is that there is no easy way to see how the two files differ if the test fails.
164+
165+
The `assertMatchesFileSnapshot($filePath)` assertion works almost the same way as the file hash assertion, except that it actually saves the whole file in the snapshots directory. If the assertion fails, it places the failed file next to the snapshot file so they can easily be manually compared. The persisted failed file is automatically deleted when the test passes. This assertion is most useful when working with binary files that should be manually compared like images or pdfs.
166+
167+
### Customizing Snapshot Ids and Directories
168+
169+
Snapshot ids are generated via the `getSnapshotId` method on the `MatchesSnapshot` trait. Override the method to customize the id. By default, a snapshot id exists of the test name, the test case name and an incrementing value, e.g. `Test__my_test_case__1`.
170+
171+
#### Example: Replacing the `__` Delimiter With `--`
172+
173+
```php
174+
protected function getSnapshotId(): string
175+
{
176+
return (new ReflectionClass($this))->getShortName().'--'.
177+
$this->getName().'--'.
178+
$this->snapshotIncrementor;
179+
}
180+
```
181+
182+
By default, snapshots are stored in a `__snapshots__` directory relative to the test class. This can be changed by overriding the `getSnapshotDirectory` method.
183+
184+
#### Example: Renaming the `__snapshots__` directory to `snapshots`
185+
186+
```php
187+
protected function getSnapshotDirectory(): string
188+
{
189+
return dirname((new ReflectionClass($this))->getFileName()).
190+
DIRECTORY_SEPARATOR.
191+
'snapshots';
192+
}
193+
```
194+
195+
### Using specific Drivers
196+
197+
The driver used to serialize the data can be specificied as second argument of the
198+
`assertMatchesSnapshot` method, so you can pick one that better suits your needs:
199+
200+
```php
201+
use Spatie\Snapshots\Drivers\JsonDriver;
202+
use Spatie\Snapshots\MatchesSnapshots;
203+
204+
class OrderTest
205+
{
206+
use MatchesSnapshots;
207+
208+
public function test_snapshot_with_json_driver()
209+
{
210+
$order = new Order(1);
211+
212+
$this->assertMatchesSnapshot($order->toJson(), new JsonDriver());
213+
}
214+
}
215+
```
216+
217+
### Writing Custom Drivers
218+
219+
Drivers ensure that different types of data can be serialized and matched in their own way. A driver is a class that implements the `Spatie\Snapshots\Driver` interface, which requires three method implementations: `serialize`, `extension` and `match`.
220+
221+
Let's take a quick quick look at the `JsonDriver`.
222+
223+
```php
224+
namespace Spatie\Snapshots\Drivers;
225+
226+
use PHPUnit\Framework\Assert;
227+
use Spatie\Snapshots\Driver;
228+
use Spatie\Snapshots\Exceptions\CantBeSerialized;
229+
230+
class JsonDriver implements Driver
231+
{
232+
public function serialize($data): string
233+
{
234+
if (! is_string($data)) {
235+
throw new CantBeSerialized('Only strings can be serialized to json');
236+
}
237+
238+
return json_encode(json_decode($data), JSON_PRETTY_PRINT).PHP_EOL;
239+
}
240+
241+
public function extension(): string
242+
{
243+
return 'json';
244+
}
245+
246+
public function match($expected, $actual)
247+
{
248+
Assert::assertJsonStringEqualsJsonString($actual, $expected);
249+
}
250+
}
251+
```
252+
253+
- The `serialize` method returns a string which will be written to the snapshot file. In the `JsonDriver`, we'll decode and re-encode the json string to ensure the snapshot has pretty printing.
254+
- We want to save json snapshots as json files, so we'll use `json` as their file extension.
255+
- When matching the expected data with the actual data, we want to use PHPUnit's built in json assertions, so we'll call the specific `assertJsonStringEqualsJsonString` method.
256+
257+
Drivers can be used by passing them as `assertMatchesSnapshot`'s second argument.
258+
259+
```php
260+
$this->assertMatchesSnapshot($something->toYaml(), new MyYamlDriver());
261+
```
262+
263+
### Usage in CI
264+
265+
When running your tests in Continuous Integration you would possibly want to disable the creation of snapshots.
266+
267+
By using the `--without-creating-snapshots` parameter or by setting the `CREATE_SNAPSHOTS` env var to `false`, PHPUnit will fail if the snapshots don't exist.
268+
269+
```bash
270+
> ./vendor/bin/phpunit -d --without-creating-snapshots
271+
272+
1) ExampleTest::test_it_matches_a_string
273+
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
274+
You can automatically create it by removing the `CREATE_SNAPSHOTS=false` env var, or `-d --no-create-snapshots` of PHPUnit's CLI arguments.
275+
```
276+
277+
### Usage with parallel testing
278+
279+
If you want to run your test in parallel with a tool like [Paratest](https://github.com/paratestphp/paratest), ou with the `php artisan test --parallel` command of Laravel, you will have to use the environment variables.
280+
281+
282+
```bash
283+
> CREATE_SNAPSHOTS=false php artisan test --parallel
284+
285+
1) ExampleTest::test_it_matches_a_string
286+
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
287+
You can automatically create it by removing the `CREATE_SNAPSHOTS=false` env var, or `-d --no-create-snapshots` of PHPUnit's CLI arguments.
288+
```
289+
290+
### A note for Windows users
291+
292+
Windows users should configure their line endings in `.gitattributes`.
293+
294+
```txt
295+
tests/**/__snapshots__/** text eol=lf
296+
```
297+
298+
## Changelog
299+
300+
Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.
301+
302+
## Testing
303+
304+
```bash
305+
composer test
306+
```
307+
308+
## Security
309+
310+
If you've found a bug regarding security please mail [[email protected]](mailto:[email protected]) instead of using the issue tracker.

composer.json

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
{
2+
"name": "spatie/phpunit-snapshot-assertions",
3+
"description": "Snapshot testing with PHPUnit",
4+
"keywords": [
5+
"spatie",
6+
"phpunit-snapshot-assertions",
7+
"phpunit",
8+
"snapshot",
9+
"assert",
10+
"testing"
11+
],
12+
"homepage": "https://github.com/spatie/phpunit-snapshot-assertions",
13+
"license": "MIT",
14+
"authors": [
15+
{
16+
"name": "Sebastian De Deyne",
17+
"email": "[email protected]",
18+
"homepage": "https://spatie.be",
19+
"role": "Developer"
20+
}
21+
],
22+
"require": {
23+
"php": "^7.3|^7.4|^8.0",
24+
"ext-dom": "*",
25+
"ext-json": "*",
26+
"ext-libxml": "*",
27+
"composer-runtime-api": "^2.0",
28+
"phpunit/phpunit": "^8.3|^9.0",
29+
"symfony/property-access": "^4.0|^5.0|^6.0",
30+
"symfony/serializer": "^4.0|^5.0|^6.0",
31+
"symfony/yaml": "^4.0|^5.0|^6.0"
32+
},
33+
"require-dev": {
34+
"phpunit/phpunit": "^9.1.0"
35+
},
36+
"autoload": {
37+
"psr-4": {
38+
"Spatie\\Snapshots\\": "src"
39+
}
40+
},
41+
"autoload-dev": {
42+
"psr-4": {
43+
"Spatie\\Snapshots\\Test\\": "tests"
44+
}
45+
},
46+
"scripts": {
47+
"test": "phpunit"
48+
},
49+
"config": {
50+
"sort-packages": true
51+
}
52+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Spatie\Snapshots\Concerns;
4+
5+
use ReflectionClass;
6+
7+
trait SnapshotDirectoryAware
8+
{
9+
/*
10+
* Determines the directory where snapshots are stored. By default a
11+
* `__snapshots__` directory is created at the same level as the test
12+
* class.
13+
*/
14+
protected function getSnapshotDirectory(): string
15+
{
16+
return dirname((new ReflectionClass($this))->getFileName()).
17+
DIRECTORY_SEPARATOR.
18+
'__snapshots__';
19+
}
20+
}

0 commit comments

Comments
 (0)