Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,41 @@
# Changelog

## 1.3.0

### Added

- Each check takes a last, optional parameter `string $message = ''`: the 23 check methods of the
trait `AssertsHtml` (`assertHtml()` and `assertHtmlNot()` had it before), the 22 expectations of
Pest and `eachMatch`. A failure shows the message first, as PHPUnit does. `NotOneNode` and
`NotAPage` show it first too. Without a message, each failure keeps its text byte for byte.
- Under `->not`, Pest lists the message among its arguments, without the region. See the README,
section One node or none.

### Fixed

- A value that is not a page stops a check with `NotAPage`, a `LogicException` like `NotOneNode`.
`Html::of()` and `html()` throw it too. Before, they failed with an `AssertionFailedError`, and
Pest's `->not` turned that into a pass. PHPUnit now counts it as an error, not as a failure.
- A missing region stops the test, also under `->not`. `within()` and `frame()` throw `NotOneNode`
where the selector finds no node or more than one. `frame()` throws `NotAPage` for a frame without
`srcdoc`. `eachMatch()` throws the new `NoMatch` where no node matches. Before, each failed with an
`AssertionFailedError`, and `->not` turned that into a pass.
- `->not->eachMatch()` stops with a `LogicException`. Before, it passed where one match failed.

### Upgrade

- A call needs no change for the message. The parameter is optional and comes last.
- A test with `->not->eachMatch()` turns the checks in the callback around instead.
- A subclass that overrides a method of `AssertsHtml` adds `string $message = ''` as its last
parameter. Without it, PHP stops with "must be compatible".
- Code that expects or catches an `AssertionFailedError` for a value that is not a page expects
`SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NotAPage`.
- A test that expects a failure for a missing region expects
`SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\NotOneNode`,
`SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NotAPage` or
`SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NoMatch`. PHPUnit counts these as errors.
- `frame()` counts as one assertion, not two.

## 1.2.0

### Added
Expand Down
57 changes: 48 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ Each check takes one of these:
- a Symfony `Response`;
- an `Html` of this package.

The package tells the kinds apart by class. None of their frameworks is a dependency.
The package tells the kinds apart by class. None of their frameworks is a dependency. Another value
stops the check with `NotAPage`, also under `->not`: a negated check cannot pass on a wrong value.

A string is parsed as a whole page, the way a browser parses it. A fragment of a table without its
table loses its tags: `<td>x</td>` alone becomes the text `x`. Wrap such a fragment in `<table>`.
Expand Down Expand Up @@ -166,12 +167,49 @@ What the checks read in detail:

A check of one node needs exactly one match. Zero or two matches throw `NotOneNode`, so a test never
reads the first of several by chance. `->not` does not turn that around: `not->toHaveSelectorText()`
on a node that is not there fails instead of passing. To say that no node is there, use
`not->toHaveSelector()`.
on a node that is not there stops with an error. It does not pass. To say that no node is there,
use `not->toHaveSelector()`.

`->not` in Pest turns a check around, and the message is Pest's own: "Expecting … not to have
selector …", without the region. `assertHtmlNot()` of the PHPUnit trait keeps the message of this
package: "(page) does not have a node matching …", with the region.
`->not` in Pest turns a check around. Pest then writes its own text, for example
`Expecting … not to have selector '[data-cart]' 'The cart is empty after checkout.'.` The text lists
each argument, also the message of the test, but not the region. `assertHtmlNot()` of the PHPUnit
trait keeps the text of this package, with the region. To give the reason and the region in Pest,
count zero nodes: `toHaveSelectorCount('[data-cart]', 0, 'The cart is empty after checkout.')`.

`within()`, `frame()` and `eachMatch()` find the region that the checks after them, or in the
callback of `eachMatch()`, read. A missing region stops the test, also under `->not`: `within()` and
`frame()` with `NotOneNode`, a frame without `srcdoc` with `NotAPage`, `eachMatch()` with `NoMatch`.
`->not->eachMatch()` stops with a `LogicException`: it would pass where one match fails. Turn the
checks in the callback around. After `within()` or `frame()`, Pest drops a `->not` before the next
`within()` or `frame()`. Turn the check after them around.

### The reason for a check

Each check takes a last, optional parameter `string $message = ''`, as the checks of PHPUnit and
Pest do. Give the reason for the check. Only the test knows it. A failure shows it first, before the
text of this package:

```php
expect($response)->toHaveSelectorCount('[data-cart] li', 3, 'The cart keeps the items of the last visit.');
self::assertHtmlSelectorCount($response, '[data-cart] li', 3, 'The cart keeps the items of the last visit.');
```

```
The cart keeps the items of the last visit.
Failed asserting that (page) has 3 nodes matching "[data-cart] li".
The selector "[data-cart] li" finds 2 nodes.
…
```

- `toHaveSelectorAttribute()` and `assertHtmlSelectorAttribute()` have an optional `$value` before
the message. Give the message by name there:
`toHaveSelectorAttribute('button', 'disabled', message: 'The form waits for the consent.')`.
- `NotOneNode`, `NotAPage` and `NoMatch` show the message first too.
- `eachMatch($selector, $callback, $message)` shows it where no node matches. Each check in the
callback takes its own message.
- `within()` and `frame()` take no message. To give a reason, check the count first:
`toHaveSelectorCount($selector, 1, $message)`.
- Under `->not`, see [One node or none](#one-node-or-none).

## Regions and values

Expand All @@ -181,7 +219,7 @@ expects and keeps checking the result, so on an `Html` the methods below chain l
```php
use function SorgeIt\PhpunitPestHtmlAssertions\Pest\html;

// A region: the page holds it exactly once, or the check fails. Every check after it looks inside it.
// A region: the page holds it exactly once, or the test stops with NotOneNode. Every check after it looks inside it.
expect(html($page))->within('[data-cart]')
->toHaveSelectorCount('li', 3)
->not->toHaveSelector('[data-errors]');
Expand All @@ -194,15 +232,16 @@ expect(html($page))->texts('[data-cart] [data-name]')->toBe(['Apple', 'Pear']);
expect(html($page))->rawTexts('[data-note]')->toBe(["Line one\nLine two"]);
expect(html($page))->attributes('[data-item]', 'data-id')->toBe(['1', '2']);

// The same checks on every match. No match is a failure: a loop over nothing would check nothing.
// The same checks on every match. No match stops the test with NoMatch: a loop over nothing would check nothing.
// `:scope` is the match itself.
expect($page)->eachMatch('[data-avatar]', fn ($avatar) => $avatar->toHaveSelectorClass(':scope', 'rounded-full'));

// Every attribute value of the region, whatever the name of the attribute.
expect(html($page)->attributeValues())->each->not->toContain('javascript:');
```

A negated check on a region that is not there would always pass. `within()` prevents that.
A negated check on a region that is not there would always pass. `within()` prevents that: a
missing region stops the test, also under `->not`.

**A region finds what lies below its element, as `querySelectorAll` of a browser does.** The element
itself is not a match: in `within('[data-cart]')`, the selector `[data-cart]` finds nothing, and
Expand Down
19 changes: 17 additions & 2 deletions resources/boost/skills/phpunit-pest-html-assertions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ Use `toBeEmptyNode`, not `toBeEmpty`: Pest has its own `toBeEmpty`.

The PHPUnit trait `SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\AssertsHtml` has the same checks as methods, for example `assertHtmlSelectorExists`, `assertHtmlSelectorTextSame` and `assertHtmlSelectorAttribute`.

## The reason for a check

Give the reason for a check as its last parameter `$message`, not as a comment. A failure shows it first. `within()` and `frame()` take no message. After the optional `$value` of `toHaveSelectorAttribute()`, give the message by name:

```php
expect($response)->toHaveSelectorCount('[data-cart] li', 3, 'The cart keeps the items of the last visit.');
expect($response)->toHaveSelectorAttribute('button[data-send]', 'disabled', message: 'The form waits for the consent.');
```

## One node or none

A check of one node (`toHaveSelectorText`, `toHaveSelectorAttribute`, `toHaveSelectorClass`, `toBeChecked`, `toBeDisabled`, `toBeEmptyNode` and similar) needs exactly one match. Zero or two matches throw `NotOneNode`, also under `->not`. To say that a node is not there, use `not->toHaveSelector()`:
Expand All @@ -59,14 +68,20 @@ A check of one node (`toHaveSelectorText`, `toHaveSelectorAttribute`, `toHaveSel
expect($response)->not->toHaveSelector('[data-errors]');
```

Under `->not`, Pest lists the message among the arguments, without the region. To give the reason and the region, count zero nodes:

```php
expect($response)->toHaveSelectorCount('[data-errors]', 0, 'A valid form shows no error.');
```

## Regions and values

`html($value)` turns a page into an `Html`. On an `Html`, the methods below chain like expectations.

```php
use function SorgeIt\PhpunitPestHtmlAssertions\Pest\html;

// A region: the page holds it exactly once. Every check after it looks inside it.
// A region: the page holds it exactly once, or the test stops with NotOneNode. Every check after it looks inside it.
expect(html($response))->within('[data-cart]')
->toHaveSelectorCount('li', 3)
->not->toHaveSelector('[data-errors]');
Expand All @@ -83,7 +98,7 @@ expect(html($response))->attributes('[data-item]', 'data-id')->toBe(['1', '2']);
expect(html($response)->attributeValues())->each->not->toContain('javascript:');
```

`eachMatch` runs the same checks on every match. No match is a failure.
`eachMatch` runs the same checks on every match. No match stops the test with `NoMatch`. Never write `->not->eachMatch()`, `->not->within()` or `->not->frame()`: turn the checks inside or after them around.

```php
expect($response)->eachMatch('[data-avatar]', fn ($avatar) => $avatar->toHaveSelectorClass(':scope', 'rounded-full'));
Expand Down
40 changes: 40 additions & 0 deletions src/PHPUnit/Assertion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace SorgeIt\PhpunitPestHtmlAssertions\PHPUnit;

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Constraint;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\NotOneNode;

/**
* Runs one check for the PHPUnit trait and the Pest expectations. The message
* of the test comes first, as PHPUnit shows it: also before `NotOneNode` and
* `NotAPage`.
*
* @internal
*/
final class Assertion
{
public static function that(mixed $html, Constraint $constraint, string $message = ''): void
{
$page = self::html($html, $message);

try {
Assert::assertThat($page, $constraint, $message);
} catch (NotOneNode $notOneNode) { // @phpstan-ignore catch.neverThrown (the constraint throws it inside assertThat())
// No `previous`: PHPUnit would print the text and the region a second time.
throw $message === '' ? $notOneNode : new NotOneNode($message."\n".$notOneNode->getMessage());
}
}

public static function html(mixed $html, string $message = ''): Html
{
try {
return Html::of($html);
} catch (NotAPage $notaPage) {
throw $message === '' ? $notaPage : new NotAPage($message."\n".$notaPage->getMessage());
}
}
}
Loading
Loading