Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Snapshots #4

Merged
merged 16 commits into from
Nov 22, 2023
Merged

Snapshots #4

merged 16 commits into from
Nov 22, 2023

Conversation

markhuot
Copy link
Owner

@markhuot markhuot commented Nov 22, 2023

Snapshots

A variety of snapshot assertions are available to help you test your HTML and DOM output in craft-pest. In many places you can simply expect an object ->toMatchSnapshot() and Pest will handle the rest for you.

The two entrypoints to snapshotting are,

  • expect($object)->toMatchSnapshot()
  • $this->assertMatchesSnapshot()

For example, responses, DOM Lists, and views are all snapshotable.

it('matches responses')->get('/')->assertMatchesSnapshot();
it('matches dom lists')->get('/')->querySelector('h1')->assertMatchesSnapshot();
it('matches views')->renderTemplate('_news/entry', $variables)->assertMatchesSnapshot();

Elements

Many elements can be snapshotted as well. When using assertions Pest will automatically handle the conversion from an Element to a snapshot.

Entry::factory()->title('foo')->create()->assertMatchesSnapshot();

Unfortunately, Pest is not smart enough to properly snapshot elements in an expectation so you must call ->toSnapshot() on them first.

it('imports entries', function () {
  $this->importEntries();
  $entry = Entry::find()->section('news')->one();

  expect($entry->toSnapshot())->toMatchSnapshot();
});

Attributes

Only a subset of attributes from the element are snapshotted so dynamic fields do not create unexpected failures. For example, the $entry->postDate defaults to the current time when the entry was generated. That means running the test on Tuesday and again on Wednesday would fail the test because the postDate would be Tuesday in the initial snapshot and Wednesday during the comparison.

If you'd like to include additional attributes in the snapshot you can pass them as an array to the ->toSnapshot() method. For example,

it('snapshots postDate', function () {
  $entry = Entry::factory()->postDate('2022-01-01')->create();

  expect($entry->toSnapshot(['postDate']))->toMatchSnapshot();
  $entry->assertMatchesSnapshot(['postDate']);
});

@markhuot markhuot merged commit d106eb4 into main Nov 22, 2023
2 checks passed
@markhuot markhuot deleted the snapshots branch November 22, 2023 17:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant