diff --git a/CHANGELOG.md b/CHANGELOG.md
index 59a4480..262545c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/README.md b/README.md
index f851fc2..2212407 100644
--- a/README.md
+++ b/README.md
@@ -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: `
x | ` alone becomes the text `x`. Wrap such a fragment in ``.
@@ -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
@@ -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]');
@@ -194,7 +232,7 @@ 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'));
@@ -202,7 +240,8 @@ expect($page)->eachMatch('[data-avatar]', fn ($avatar) => $avatar->toHaveSelecto
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
diff --git a/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md b/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md
index 99954e6..c70c109 100644
--- a/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md
+++ b/resources/boost/skills/phpunit-pest-html-assertions/SKILL.md
@@ -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()`:
@@ -59,6 +68,12 @@ 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.
@@ -66,7 +81,7 @@ expect($response)->not->toHaveSelector('[data-errors]');
```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]');
@@ -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'));
diff --git a/src/PHPUnit/Assertion.php b/src/PHPUnit/Assertion.php
new file mode 100644
index 0000000..6681941
--- /dev/null
+++ b/src/PHPUnit/Assertion.php
@@ -0,0 +1,40 @@
+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());
+ }
+ }
+}
diff --git a/src/PHPUnit/AssertsHtml.php b/src/PHPUnit/AssertsHtml.php
index 0d92b3b..b4a4676 100644
--- a/src/PHPUnit/AssertsHtml.php
+++ b/src/PHPUnit/AssertsHtml.php
@@ -4,7 +4,6 @@
namespace SorgeIt\PhpunitPestHtmlAssertions\PHPUnit;
-use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Constraint;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\AppearsBefore;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\HasAnySelectorText;
@@ -39,126 +38,126 @@ trait AssertsHtml
{
public static function assertHtml(mixed $html, Constraint $constraint, string $message = ''): void
{
- Assert::assertThat(Html::of($html), $constraint, $message);
+ Assertion::that($html, $constraint, $message);
}
public static function assertHtmlNot(mixed $html, Constraint&RegionCheck $constraint, string $message = ''): void
{
- Assert::assertThat(Html::of($html), new Not($constraint), $message);
+ Assertion::that($html, new Not($constraint), $message);
}
- public static function assertHtmlSelectorExists(mixed $html, string $selector): void
+ public static function assertHtmlSelectorExists(mixed $html, string $selector, string $message = ''): void
{
- self::assertHtml($html, new HasSelector($selector));
+ self::assertHtml($html, new HasSelector($selector), $message);
}
- public static function assertHtmlSelectorNotExists(mixed $html, string $selector): void
+ public static function assertHtmlSelectorNotExists(mixed $html, string $selector, string $message = ''): void
{
- self::assertHtmlNot($html, new HasSelector($selector));
+ self::assertHtmlNot($html, new HasSelector($selector), $message);
}
- public static function assertHtmlSelectorCount(mixed $html, string $selector, int $count): void
+ public static function assertHtmlSelectorCount(mixed $html, string $selector, int $count, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorCount($selector, $count));
+ self::assertHtml($html, new HasSelectorCount($selector, $count), $message);
}
- public static function assertHtmlSelectorCountAtLeast(mixed $html, string $selector, int $count): void
+ public static function assertHtmlSelectorCountAtLeast(mixed $html, string $selector, int $count, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorCountAtLeast($selector, $count));
+ self::assertHtml($html, new HasSelectorCountAtLeast($selector, $count), $message);
}
- public static function assertHtmlSelectorTextSame(mixed $html, string $selector, string $text): void
+ public static function assertHtmlSelectorTextSame(mixed $html, string $selector, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorText($selector, $text));
+ self::assertHtml($html, new HasSelectorText($selector, $text), $message);
}
- public static function assertHtmlSelectorTextContains(mixed $html, string $selector, string $text): void
+ public static function assertHtmlSelectorTextContains(mixed $html, string $selector, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorTextContaining($selector, $text));
+ self::assertHtml($html, new HasSelectorTextContaining($selector, $text), $message);
}
- public static function assertHtmlAnySelectorTextSame(mixed $html, string $selector, string $text): void
+ public static function assertHtmlAnySelectorTextSame(mixed $html, string $selector, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasAnySelectorText($selector, $text));
+ self::assertHtml($html, new HasAnySelectorText($selector, $text), $message);
}
- public static function assertHtmlAnySelectorTextContains(mixed $html, string $selector, string $text): void
+ public static function assertHtmlAnySelectorTextContains(mixed $html, string $selector, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasAnySelectorTextContaining($selector, $text));
+ self::assertHtml($html, new HasAnySelectorTextContaining($selector, $text), $message);
}
- public static function assertHtmlSelectorAttribute(mixed $html, string $selector, string $attribute, ?string $value = null): void
+ public static function assertHtmlSelectorAttribute(mixed $html, string $selector, string $attribute, ?string $value = null, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorAttribute($selector, $attribute, $value));
+ self::assertHtml($html, new HasSelectorAttribute($selector, $attribute, $value), $message);
}
- public static function assertHtmlSelectorAttributeContains(mixed $html, string $selector, string $attribute, string $part): void
+ public static function assertHtmlSelectorAttributeContains(mixed $html, string $selector, string $attribute, string $part, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorAttributeContaining($selector, $attribute, $part));
+ self::assertHtml($html, new HasSelectorAttributeContaining($selector, $attribute, $part), $message);
}
- public static function assertHtmlSelectorAttributeNamed(mixed $html, string $selector, string $prefix): void
+ public static function assertHtmlSelectorAttributeNamed(mixed $html, string $selector, string $prefix, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorAttributeNamed($selector, $prefix));
+ self::assertHtml($html, new HasSelectorAttributeNamed($selector, $prefix), $message);
}
- public static function assertHtmlSelectorClass(mixed $html, string $selector, string $classes): void
+ public static function assertHtmlSelectorClass(mixed $html, string $selector, string $classes, string $message = ''): void
{
- self::assertHtml($html, new HasSelectorClass($selector, $classes));
+ self::assertHtml($html, new HasSelectorClass($selector, $classes), $message);
}
- public static function assertHtmlTextSame(mixed $html, string $text): void
+ public static function assertHtmlTextSame(mixed $html, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasText($text));
+ self::assertHtml($html, new HasText($text), $message);
}
- public static function assertHtmlTextContains(mixed $html, string $text): void
+ public static function assertHtmlTextContains(mixed $html, string $text, string $message = ''): void
{
- self::assertHtml($html, new HasTextContaining($text));
+ self::assertHtml($html, new HasTextContaining($text), $message);
}
- public static function assertHtmlTextCount(mixed $html, string $text, int $count): void
+ public static function assertHtmlTextCount(mixed $html, string $text, int $count, string $message = ''): void
{
- self::assertHtml($html, new HasTextCount($text, $count));
+ self::assertHtml($html, new HasTextCount($text, $count), $message);
}
- public static function assertHtmlSelectorBefore(mixed $html, string $first, string $second): void
+ public static function assertHtmlSelectorBefore(mixed $html, string $first, string $second, string $message = ''): void
{
- self::assertHtml($html, new AppearsBefore($first, $second));
+ self::assertHtml($html, new AppearsBefore($first, $second), $message);
}
- public static function assertHtmlPageTitleSame(mixed $html, string $title): void
+ public static function assertHtmlPageTitleSame(mixed $html, string $title, string $message = ''): void
{
- self::assertHtml($html, new HasTitle($title));
+ self::assertHtml($html, new HasTitle($title), $message);
}
- public static function assertHtmlInputValueSame(mixed $html, string $name, string $value): void
+ public static function assertHtmlInputValueSame(mixed $html, string $name, string $value, string $message = ''): void
{
- self::assertHtml($html, new HasInputValue($name, $value));
+ self::assertHtml($html, new HasInputValue($name, $value), $message);
}
- public static function assertHtmlCheckboxChecked(mixed $html, string $selector): void
+ public static function assertHtmlCheckboxChecked(mixed $html, string $selector, string $message = ''): void
{
- self::assertHtml($html, new IsChecked($selector));
+ self::assertHtml($html, new IsChecked($selector), $message);
}
- public static function assertHtmlSelectedOption(mixed $html, string $selector, string $value): void
+ public static function assertHtmlSelectedOption(mixed $html, string $selector, string $value, string $message = ''): void
{
- self::assertHtml($html, new HasSelectedOption($selector, $value));
+ self::assertHtml($html, new HasSelectedOption($selector, $value), $message);
}
- public static function assertHtmlSelectorDisabled(mixed $html, string $selector): void
+ public static function assertHtmlSelectorDisabled(mixed $html, string $selector, string $message = ''): void
{
- self::assertHtml($html, new IsDisabled($selector));
+ self::assertHtml($html, new IsDisabled($selector), $message);
}
- public static function assertHtmlLink(mixed $html, string $text, string $href): void
+ public static function assertHtmlLink(mixed $html, string $text, string $href, string $message = ''): void
{
- self::assertHtml($html, new HasLink($text, $href));
+ self::assertHtml($html, new HasLink($text, $href), $message);
}
- public static function assertHtmlSelectorEmpty(mixed $html, string $selector): void
+ public static function assertHtmlSelectorEmpty(mixed $html, string $selector, string $message = ''): void
{
- self::assertHtml($html, new IsEmpty($selector));
+ self::assertHtml($html, new IsEmpty($selector), $message);
}
}
diff --git a/src/PHPUnit/Constraint/One.php b/src/PHPUnit/Constraint/One.php
index 8cae095..8c9f3ca 100644
--- a/src/PHPUnit/Constraint/One.php
+++ b/src/PHPUnit/Constraint/One.php
@@ -14,14 +14,15 @@
*/
final class One
{
- public static function element(Html $html, string $selector): DOMElement
+ public static function element(Html $html, string $selector, string $check = 'a check of one node'): DOMElement
{
$elements = $html->elements($selector);
if (count($elements) !== 1) {
throw new NotOneNode(sprintf(
- "%s: a check of one node needs exactly one match. %s\n\nIn %s:\n%s",
+ "%s: %s needs exactly one match. %s\n\nIn %s:\n%s",
$html->path(),
+ $check,
self::count($html, $selector),
$html->path(),
$html->excerpt(),
diff --git a/src/PHPUnit/Html.php b/src/PHPUnit/Html.php
index ae7b9d7..80fe734 100644
--- a/src/PHPUnit/Html.php
+++ b/src/PHPUnit/Html.php
@@ -14,6 +14,7 @@
use PHPUnit\Framework\Assert;
use Psr\Http\Message\ResponseInterface;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\HasSelectorCount;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\One;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
@@ -58,28 +59,31 @@ public static function of(mixed $value): self
$value instanceof Testable => self::parse($value->html()),
$value instanceof ResponseInterface => self::parse((string) $value->getBody()),
$value instanceof Response => self::parse((string) $value->getContent()),
- default => Assert::fail(sprintf(
+ default => throw new NotAPage(sprintf(
'A check of HTML reads a string, an Html, a Crawler, a TestResponse, a TestView, a TestComponent, a Livewire Testable, a PSR-7 response or a response of Symfony, not %s.',
get_debug_type($value),
)),
};
}
- /** The one node the selector finds, as a region of its own: zero or two are a failure, not an empty region. */
+ /**
+ * The one node the selector finds, as a region of its own. Zero or two stop
+ * the test with `NotOneNode`, which no `->not` turns into a pass.
+ */
public function within(string $selector): self
{
- Assert::assertThat($this, new HasSelectorCount($selector, 1));
-
- return new self($this->document, $this->elements($selector)[0], [...$this->path, $selector]);
+ return $this->region($selector, 'within()');
}
- /** The document in the `srcdoc` of the one frame the selector finds. */
+ /** The document in the `srcdoc` of the one frame the selector finds. A frame without it is `NotAPage`. */
public function frame(string $selector): self
{
- $frame = $this->within($selector);
- $document = $frame->scope?->getAttribute('srcdoc');
+ $frame = $this->region($selector, 'frame()');
+ $document = $frame->scope?->getAttribute('srcdoc') ?? '';
- Assert::assertNotEmpty($document, sprintf('The frame %s has no srcdoc.', $frame->path()));
+ if ($document === '') {
+ throw new NotAPage(sprintf('The frame %s has no srcdoc, so it holds no page.', $frame->path()));
+ }
return new self(new Crawler($document), null, [...$frame->path, 'srcdoc']);
}
@@ -245,6 +249,16 @@ private function isBelow(DOMNode $node, DOMElement $scope): bool
return false;
}
+ private function region(string $selector, string $check): self
+ {
+ $element = One::element($this, $selector, $check);
+
+ // A region counts as one assertion, as it did when it asserted the count.
+ Assert::assertThat($this, new HasSelectorCount($selector, 1));
+
+ return new self($this->document, $element, [...$this->path, $selector]);
+ }
+
/** @return list */
private function elementsBelow(DOMElement $root): array
{
diff --git a/src/PHPUnit/NoMatch.php b/src/PHPUnit/NoMatch.php
new file mode 100644
index 0000000..2baff0a
--- /dev/null
+++ b/src/PHPUnit/NoMatch.php
@@ -0,0 +1,13 @@
+not` catches a failure, not this.
+ */
+final class NoMatch extends LogicException {}
diff --git a/src/PHPUnit/NotAPage.php b/src/PHPUnit/NotAPage.php
new file mode 100644
index 0000000..318bf7d
--- /dev/null
+++ b/src/PHPUnit/NotAPage.php
@@ -0,0 +1,13 @@
+not` catches a failure, and a negated check must not pass.
+ */
+final class NotAPage extends LogicException {}
diff --git a/src/Pest/Expectations.php b/src/Pest/Expectations.php
index 83251d9..e7b17bf 100644
--- a/src/Pest/Expectations.php
+++ b/src/Pest/Expectations.php
@@ -4,9 +4,12 @@
namespace SorgeIt\PhpunitPestHtmlAssertions\Pest;
+use LogicException;
use Pest\Expectation;
-use PHPUnit\Framework\Assert;
+use Pest\Expectations\OppositeExpectation;
use PHPUnit\Framework\Constraint\Constraint;
+use ReflectionFunction;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Assertion;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\AppearsBefore;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\HasAnySelectorText;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\HasAnySelectorTextContaining;
@@ -29,7 +32,9 @@
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\IsChecked;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\IsDisabled;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\IsEmpty;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\One;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Html;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NoMatch;
/**
* The constraints of the PHPUnit part as Pest expectations. `->not` turns any
@@ -43,56 +48,71 @@ public static function register(): void
$check = self::check(...);
$eachMatch = self::eachMatch(...);
- expect()->extend('toHaveSelector', fn (string $selector): Expectation => $check($this, new HasSelector($selector)));
- expect()->extend('toHaveSelectorCount', fn (string $selector, int $count): Expectation => $check($this, new HasSelectorCount($selector, $count)));
- expect()->extend('toHaveSelectorCountAtLeast', fn (string $selector, int $count): Expectation => $check($this, new HasSelectorCountAtLeast($selector, $count)));
- expect()->extend('toHaveSelectorText', fn (string $selector, string $text): Expectation => $check($this, new HasSelectorText($selector, $text)));
- expect()->extend('toHaveSelectorTextContaining', fn (string $selector, string $text): Expectation => $check($this, new HasSelectorTextContaining($selector, $text)));
- expect()->extend('toHaveAnySelectorText', fn (string $selector, string $text): Expectation => $check($this, new HasAnySelectorText($selector, $text)));
- expect()->extend('toHaveAnySelectorTextContaining', fn (string $selector, string $text): Expectation => $check($this, new HasAnySelectorTextContaining($selector, $text)));
- expect()->extend('toHaveSelectorAttribute', fn (string $selector, string $attribute, ?string $value = null): Expectation => $check($this, new HasSelectorAttribute($selector, $attribute, $value)));
- expect()->extend('toHaveSelectorAttributeContaining', fn (string $selector, string $attribute, string $part): Expectation => $check($this, new HasSelectorAttributeContaining($selector, $attribute, $part)));
- expect()->extend('toHaveSelectorAttributeNamed', fn (string $selector, string $prefix): Expectation => $check($this, new HasSelectorAttributeNamed($selector, $prefix)));
- expect()->extend('toHaveSelectorClass', fn (string $selector, string $classes): Expectation => $check($this, new HasSelectorClass($selector, $classes)));
- expect()->extend('toHaveText', fn (string $text): Expectation => $check($this, new HasText($text)));
- expect()->extend('toHaveTextContaining', fn (string $text): Expectation => $check($this, new HasTextContaining($text)));
- expect()->extend('toHaveTextCount', fn (string $text, int $count): Expectation => $check($this, new HasTextCount($text, $count)));
- expect()->extend('toAppearBefore', fn (string $first, string $second): Expectation => $check($this, new AppearsBefore($first, $second)));
- expect()->extend('toHaveTitle', fn (string $title): Expectation => $check($this, new HasTitle($title)));
- expect()->extend('toHaveInputValue', fn (string $name, string $value): Expectation => $check($this, new HasInputValue($name, $value)));
- expect()->extend('toBeChecked', fn (string $selector): Expectation => $check($this, new IsChecked($selector)));
- expect()->extend('toHaveSelectedOption', fn (string $selector, string $value): Expectation => $check($this, new HasSelectedOption($selector, $value)));
- expect()->extend('toBeDisabled', fn (string $selector): Expectation => $check($this, new IsDisabled($selector)));
- expect()->extend('toHaveLink', fn (string $text, string $href): Expectation => $check($this, new HasLink($text, $href)));
- expect()->extend('toBeEmptyNode', fn (string $selector): Expectation => $check($this, new IsEmpty($selector)));
-
- expect()->extend('eachMatch', fn (string $selector, callable $callback): Expectation => $eachMatch($this, $selector, $callback));
+ expect()->extend('toHaveSelector', fn (string $selector, string $message = ''): Expectation => $check($this, new HasSelector($selector), $message));
+ expect()->extend('toHaveSelectorCount', fn (string $selector, int $count, string $message = ''): Expectation => $check($this, new HasSelectorCount($selector, $count), $message));
+ expect()->extend('toHaveSelectorCountAtLeast', fn (string $selector, int $count, string $message = ''): Expectation => $check($this, new HasSelectorCountAtLeast($selector, $count), $message));
+ expect()->extend('toHaveSelectorText', fn (string $selector, string $text, string $message = ''): Expectation => $check($this, new HasSelectorText($selector, $text), $message));
+ expect()->extend('toHaveSelectorTextContaining', fn (string $selector, string $text, string $message = ''): Expectation => $check($this, new HasSelectorTextContaining($selector, $text), $message));
+ expect()->extend('toHaveAnySelectorText', fn (string $selector, string $text, string $message = ''): Expectation => $check($this, new HasAnySelectorText($selector, $text), $message));
+ expect()->extend('toHaveAnySelectorTextContaining', fn (string $selector, string $text, string $message = ''): Expectation => $check($this, new HasAnySelectorTextContaining($selector, $text), $message));
+ expect()->extend('toHaveSelectorAttribute', fn (string $selector, string $attribute, ?string $value = null, string $message = ''): Expectation => $check($this, new HasSelectorAttribute($selector, $attribute, $value), $message));
+ expect()->extend('toHaveSelectorAttributeContaining', fn (string $selector, string $attribute, string $part, string $message = ''): Expectation => $check($this, new HasSelectorAttributeContaining($selector, $attribute, $part), $message));
+ expect()->extend('toHaveSelectorAttributeNamed', fn (string $selector, string $prefix, string $message = ''): Expectation => $check($this, new HasSelectorAttributeNamed($selector, $prefix), $message));
+ expect()->extend('toHaveSelectorClass', fn (string $selector, string $classes, string $message = ''): Expectation => $check($this, new HasSelectorClass($selector, $classes), $message));
+ expect()->extend('toHaveText', fn (string $text, string $message = ''): Expectation => $check($this, new HasText($text), $message));
+ expect()->extend('toHaveTextContaining', fn (string $text, string $message = ''): Expectation => $check($this, new HasTextContaining($text), $message));
+ expect()->extend('toHaveTextCount', fn (string $text, int $count, string $message = ''): Expectation => $check($this, new HasTextCount($text, $count), $message));
+ expect()->extend('toAppearBefore', fn (string $first, string $second, string $message = ''): Expectation => $check($this, new AppearsBefore($first, $second), $message));
+ expect()->extend('toHaveTitle', fn (string $title, string $message = ''): Expectation => $check($this, new HasTitle($title), $message));
+ expect()->extend('toHaveInputValue', fn (string $name, string $value, string $message = ''): Expectation => $check($this, new HasInputValue($name, $value), $message));
+ expect()->extend('toBeChecked', fn (string $selector, string $message = ''): Expectation => $check($this, new IsChecked($selector), $message));
+ expect()->extend('toHaveSelectedOption', fn (string $selector, string $value, string $message = ''): Expectation => $check($this, new HasSelectedOption($selector, $value), $message));
+ expect()->extend('toBeDisabled', fn (string $selector, string $message = ''): Expectation => $check($this, new IsDisabled($selector), $message));
+ expect()->extend('toHaveLink', fn (string $text, string $href, string $message = ''): Expectation => $check($this, new HasLink($text, $href), $message));
+ expect()->extend('toBeEmptyNode', fn (string $selector, string $message = ''): Expectation => $check($this, new IsEmpty($selector), $message));
+
+ expect()->extend('eachMatch', fn (string $selector, callable $callback, string $message = ''): Expectation => $eachMatch($this, $selector, $callback, $message));
}
/**
* @param Expectation $expectation
* @return Expectation
*/
- private static function check(Expectation $expectation, Constraint $constraint): Expectation
+ private static function check(Expectation $expectation, Constraint $constraint, string $message): Expectation
{
- Assert::assertThat(Html::of($expectation->value), $constraint);
+ Assertion::that($expectation->value, $constraint, $message);
return $expectation;
}
/**
- * The same checks on every node the selector finds. No match is a
- * failure: a loop over nothing would pass and check nothing.
+ * The same checks on every node the selector finds. No match stops the
+ * test with `NoMatch`: a loop over nothing would pass, also under `->not`.
*
* @param Expectation $expectation
* @param callable(Expectation, int): mixed $callback
* @return Expectation
*/
- private static function eachMatch(Expectation $expectation, string $selector, callable $callback): Expectation
+ private static function eachMatch(Expectation $expectation, string $selector, callable $callback, string $message): Expectation
{
- $html = Html::of($expectation->value);
+ if (self::isTurnedAround()) {
+ throw new LogicException(($message === '' ? '' : $message."\n").'eachMatch() cannot be turned around: ->not would pass where one match fails. Turn the checks in the callback around.');
+ }
+
+ $html = Assertion::html($expectation->value, $message);
+
+ if ($html->count($selector) === 0) {
+ throw new NoMatch(sprintf(
+ "%s%s: eachMatch() needs at least one match. %s\n\nIn %s:\n%s",
+ $message === '' ? '' : $message."\n",
+ $html->path(),
+ One::count($html, $selector),
+ $html->path(),
+ $html->excerpt(),
+ ));
+ }
- Assert::assertThat($html, new HasSelector($selector));
+ Assertion::that($html, new HasSelector($selector), $message);
foreach ($html->matches($selector) as $index => $region) {
$callback(expect($region), $index);
@@ -100,4 +120,31 @@ private static function eachMatch(Expectation $expectation, string $selector, ca
return $expectation;
}
+
+ /**
+ * Whether Pest's `->not` called this expectation. Pest's own frames lie in
+ * between; the first frame outside Pest decides. A test that wraps the
+ * call, for example in `->not->toThrow()`, stops the search with its closure.
+ */
+ private static function isTurnedAround(): bool
+ {
+ foreach (array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 1) as $frame) {
+ $class = $frame['class'] ?? null;
+
+ if ($class === OppositeExpectation::class) {
+ return true;
+ }
+
+ // Pest calls through `call_user_func_array()`; a function of the test is a frame outside Pest.
+ $outsidePest = $class === null
+ ? ! function_exists($frame['function']) || ! (new ReflectionFunction($frame['function']))->isInternal()
+ : $class !== self::class && ! str_starts_with($class, 'Pest\\');
+
+ if ($outsidePest) {
+ return false;
+ }
+ }
+
+ return false;
+ }
}
diff --git a/tests/PHPUnit/AssertsHtmlTest.php b/tests/PHPUnit/AssertsHtmlTest.php
index 2b61b95..21fb475 100644
--- a/tests/PHPUnit/AssertsHtmlTest.php
+++ b/tests/PHPUnit/AssertsHtmlTest.php
@@ -21,6 +21,7 @@
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\NotOneNode;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\RegionCheck;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Html;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NotAPage;
use SorgeIt\PhpunitPestHtmlAssertions\Tests\Page;
/** Each check of the trait once green and once red, on the same page. */
@@ -59,34 +60,34 @@ public static function passing(): iterable
yield 'an empty node' => [fn (string $page) => self::assertHtmlSelectorEmpty($page, '[data-empty]')];
}
- /** @return iterable */
+ /** @return iterable */
public static function failing(): iterable
{
- yield 'no such node' => [fn (string $page) => self::assertHtmlSelectorExists($page, '[data-here]')];
- yield 'a node that is there' => [fn (string $page) => self::assertHtmlSelectorNotExists($page, '[data-people]')];
- yield 'another count' => [fn (string $page) => self::assertHtmlSelectorCount($page, '[data-name]', 3)];
- yield 'too few' => [fn (string $page) => self::assertHtmlSelectorCountAtLeast($page, '[data-name]', 3)];
- yield 'another text' => [fn (string $page) => self::assertHtmlSelectorTextSame($page, 'h1', 'Review')];
- yield 'a part not in the text' => [fn (string $page) => self::assertHtmlSelectorTextContains($page, 'h1', 'Montag')];
- yield 'a text of no node' => [fn (string $page) => self::assertHtmlAnySelectorTextSame($page, '[data-name]', 'Clara')];
- yield 'a part of no text' => [fn (string $page) => self::assertHtmlAnySelectorTextContains($page, '[data-name]', 'Cla')];
- yield 'another attribute value' => [fn (string $page) => self::assertHtmlSelectorAttribute($page, '[data-link]', 'href', '/in')];
- yield 'a missing attribute' => [fn (string $page) => self::assertHtmlSelectorAttribute($page, '[data-cancel]', 'disabled')];
- yield 'a part not in the attribute' => [fn (string $page) => self::assertHtmlSelectorAttributeContains($page, '[data-link]', 'href', 'u=2')];
- yield 'no attribute of that name' => [fn (string $page) => self::assertHtmlSelectorAttributeNamed($page, '[data-head]', 'wire:poll')];
- yield 'a missing class' => [fn (string $page) => self::assertHtmlSelectorClass($page, '[data-name="Ben"]', 'bg-blue-500')];
- yield 'another text of a region' => [fn (string $page) => self::assertHtmlTextSame(Html::of($page)->within('[data-people]'), 'Anna Ben')];
+ yield 'no such node' => [fn (string $page, string $message = '') => self::assertHtmlSelectorExists($page, '[data-here]', $message)];
+ yield 'a node that is there' => [fn (string $page, string $message = '') => self::assertHtmlSelectorNotExists($page, '[data-people]', $message)];
+ yield 'another count' => [fn (string $page, string $message = '') => self::assertHtmlSelectorCount($page, '[data-name]', 3, $message)];
+ yield 'too few' => [fn (string $page, string $message = '') => self::assertHtmlSelectorCountAtLeast($page, '[data-name]', 3, $message)];
+ yield 'another text' => [fn (string $page, string $message = '') => self::assertHtmlSelectorTextSame($page, 'h1', 'Review', $message)];
+ yield 'a part not in the text' => [fn (string $page, string $message = '') => self::assertHtmlSelectorTextContains($page, 'h1', 'Montag', $message)];
+ yield 'a text of no node' => [fn (string $page, string $message = '') => self::assertHtmlAnySelectorTextSame($page, '[data-name]', 'Clara', $message)];
+ yield 'a part of no text' => [fn (string $page, string $message = '') => self::assertHtmlAnySelectorTextContains($page, '[data-name]', 'Cla', $message)];
+ yield 'another attribute value' => [fn (string $page, string $message = '') => self::assertHtmlSelectorAttribute($page, '[data-link]', 'href', '/in', $message)];
+ yield 'a missing attribute' => [fn (string $page, string $message = '') => self::assertHtmlSelectorAttribute($page, '[data-cancel]', 'disabled', message: $message)];
+ yield 'a part not in the attribute' => [fn (string $page, string $message = '') => self::assertHtmlSelectorAttributeContains($page, '[data-link]', 'href', 'u=2', $message)];
+ yield 'no attribute of that name' => [fn (string $page, string $message = '') => self::assertHtmlSelectorAttributeNamed($page, '[data-head]', 'wire:poll', $message)];
+ yield 'a missing class' => [fn (string $page, string $message = '') => self::assertHtmlSelectorClass($page, '[data-name="Ben"]', 'bg-blue-500', $message)];
+ yield 'another text of a region' => [fn (string $page, string $message = '') => self::assertHtmlTextSame(Html::of($page)->within('[data-people]'), 'Anna Ben', $message)];
// A script is no text a reader gets.
- yield 'the text of a script' => [fn (string $page) => self::assertHtmlTextContains($page, 'alert(1)')];
- yield 'a text once' => [fn (string $page) => self::assertHtmlTextCount($page, 'Review', 1)];
- yield 'the other order' => [fn (string $page) => self::assertHtmlSelectorBefore($page, '[data-body]', '[data-head]')];
- yield 'another title' => [fn (string $page) => self::assertHtmlPageTitleSame($page, 'Another page')];
- yield 'another value' => [fn (string $page) => self::assertHtmlInputValueSame($page, 'email', 'ben@example.test')];
- yield 'an unchecked box' => [fn (string $page) => self::assertHtmlCheckboxChecked($page, 'input[name="email"]')];
- yield 'another option' => [fn (string $page) => self::assertHtmlSelectedOption($page, '[data-day]', 'mo')];
- yield 'an enabled button' => [fn (string $page) => self::assertHtmlSelectorDisabled($page, '[data-cancel]')];
- yield 'a link to elsewhere' => [fn (string $page) => self::assertHtmlLink($page, 'Next', '/in')];
- yield 'a node with text' => [fn (string $page) => self::assertHtmlSelectorEmpty($page, 'h1')];
+ yield 'the text of a script' => [fn (string $page, string $message = '') => self::assertHtmlTextContains($page, 'alert(1)', $message)];
+ yield 'a text once' => [fn (string $page, string $message = '') => self::assertHtmlTextCount($page, 'Review', 1, $message)];
+ yield 'the other order' => [fn (string $page, string $message = '') => self::assertHtmlSelectorBefore($page, '[data-body]', '[data-head]', $message)];
+ yield 'another title' => [fn (string $page, string $message = '') => self::assertHtmlPageTitleSame($page, 'Another page', $message)];
+ yield 'another value' => [fn (string $page, string $message = '') => self::assertHtmlInputValueSame($page, 'email', 'ben@example.test', $message)];
+ yield 'an unchecked box' => [fn (string $page, string $message = '') => self::assertHtmlCheckboxChecked($page, 'input[name="email"]', $message)];
+ yield 'another option' => [fn (string $page, string $message = '') => self::assertHtmlSelectedOption($page, '[data-day]', 'mo', $message)];
+ yield 'an enabled button' => [fn (string $page, string $message = '') => self::assertHtmlSelectorDisabled($page, '[data-cancel]', $message)];
+ yield 'a link to elsewhere' => [fn (string $page, string $message = '') => self::assertHtmlLink($page, 'Next', '/in', $message)];
+ yield 'a node with text' => [fn (string $page, string $message = '') => self::assertHtmlSelectorEmpty($page, 'h1', $message)];
}
/** @return iterable */
@@ -109,7 +110,7 @@ public function test_it_passes_where_the_page_holds_what_is_asked(Closure $check
$this->addToAssertionCount(1);
}
- /** @param Closure(string): void $check */
+ /** @param Closure(string, string=): void $check */
#[DataProvider('failing')]
public function test_it_fails_where_the_page_does_not(Closure $check): void
{
@@ -118,6 +119,78 @@ public function test_it_fails_where_the_page_does_not(Closure $check): void
$check(Page::HTML);
}
+ /** @param Closure(string, string): void $check */
+ #[DataProvider('failing')]
+ public function test_a_failure_shows_the_message_of_the_test_before_its_own(Closure $check): void
+ {
+ try {
+ $check(Page::HTML, 'The cart shows what the customer chose.');
+ } catch (ExpectationFailedException $expectationFailedException) {
+ self::assertStringStartsWith("The cart shows what the customer chose.\nFailed asserting that (page", $expectationFailedException->getMessage());
+
+ return;
+ }
+
+ self::fail('The check passed.');
+ }
+
+ public function test_a_failure_without_a_message_keeps_its_text(): void
+ {
+ try {
+ // A whole page: the parsers of Symfony 7.4 and 8.1 add a missing head differently.
+ self::assertHtmlSelectorCount('', 'li', 2);
+ } catch (ExpectationFailedException $expectationFailedException) {
+ self::assertSame(
+ "Failed asserting that (page) has 2 nodes matching \"li\".\nThe selector \"li\" finds 1 nodes.\n\nIn (page):\n \n \n \n \n - \n a",
+ $expectationFailedException->getMessage(),
+ );
+
+ return;
+ }
+
+ self::fail('The check passed.');
+ }
+
+ public function test_a_check_of_one_node_shows_the_message_of_the_test_before_its_own(): void
+ {
+ try {
+ self::assertHtmlSelectorTextSame(Page::HTML, '[data-name]', 'Anna Example', 'The total shows the sum.');
+ } catch (NotOneNode $notOneNode) {
+ self::assertStringStartsWith("The total shows the sum.\n(page): a check of one node needs exactly one match.", $notOneNode->getMessage());
+ self::assertNotInstanceOf(NotOneNode::class, $notOneNode->getPrevious(), 'PHPUnit prints a previous exception a second time.');
+
+ return;
+ }
+
+ self::fail('The check passed on two nodes.');
+ }
+
+ public function test_a_check_of_one_node_without_a_message_keeps_its_text(): void
+ {
+ try {
+ self::assertHtmlSelectorTextSame(Page::HTML, '[data-name]', 'Anna Example');
+ } catch (NotOneNode $notOneNode) {
+ self::assertStringStartsWith('(page): a check of one node needs exactly one match.', $notOneNode->getMessage());
+
+ return;
+ }
+
+ self::fail('The check passed on two nodes.');
+ }
+
+ public function test_a_value_that_is_not_a_page_shows_the_message_of_the_test_first(): void
+ {
+ try {
+ self::assertHtmlSelectorExists(42, 'p', 'The page renders.');
+ } catch (NotAPage $notaPage) {
+ self::assertStringStartsWith("The page renders.\nA check of HTML reads ", $notaPage->getMessage());
+
+ return;
+ }
+
+ self::fail('The check passed on a number.');
+ }
+
public function test_a_failure_names_the_path_what_was_found_and_the_region(): void
{
try {
diff --git a/tests/PHPUnit/HtmlTest.php b/tests/PHPUnit/HtmlTest.php
index f4791db..f486d79 100644
--- a/tests/PHPUnit/HtmlTest.php
+++ b/tests/PHPUnit/HtmlTest.php
@@ -7,10 +7,10 @@
use Illuminate\Testing\TestResponse;
use InvalidArgumentException;
use Nyholm\Psr7\Response as Psr7Response;
-use PHPUnit\Framework\AssertionFailedError;
-use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\NotOneNode;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Html;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NotAPage;
use SorgeIt\PhpunitPestHtmlAssertions\Tests\Page;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response;
@@ -40,7 +40,7 @@ public function test_it_reads_each_kind_it_names(): void
public function test_it_names_the_kinds_it_reads_where_it_gets_another(): void
{
- $this->expectException(AssertionFailedError::class);
+ $this->expectException(NotAPage::class);
$this->expectExceptionMessage('a string, an Html, a Crawler, a TestResponse, a TestView, a TestComponent, a Livewire Testable, a PSR-7 response or a response of Symfony, not int');
Html::of(42);
@@ -95,19 +95,19 @@ public function test_attribute_values_lists_every_value_in_the_region(): void
self::assertNotContains('/out?u=1', $values);
}
- public function test_within_fails_where_the_region_is_missing_or_there_twice(): void
+ public function test_within_stops_where_the_region_is_missing_or_there_twice(): void
{
- foreach (['[data-here]', '[data-name]'] as $selector) {
+ foreach (['[data-here]' => 0, '[data-name]' => 2] as $selector => $count) {
try {
Html::of(Page::HTML)->within($selector);
- } catch (ExpectationFailedException) {
+ } catch (NotOneNode $notOneNode) {
+ self::assertStringStartsWith(sprintf('(page): within() needs exactly one match. The selector "%s" finds %d nodes.', $selector, $count), $notOneNode->getMessage());
+
continue;
}
self::fail('within() passed on '.$selector);
}
-
- $this->addToAssertionCount(1);
}
public function test_frame_reads_the_document_in_the_srcdoc(): void
@@ -118,13 +118,22 @@ public function test_frame_reads_the_document_in_the_srcdoc(): void
self::assertSame('(page) > [data-mail] > srcdoc', $mail->path());
}
- public function test_frame_fails_on_a_node_without_srcdoc(): void
+ public function test_frame_stops_on_a_node_without_srcdoc(): void
{
- $this->expectException(AssertionFailedError::class);
+ $this->expectException(NotAPage::class);
+ $this->expectExceptionMessage('The frame (page) > [data-head] has no srcdoc, so it holds no page.');
Html::of(Page::HTML)->frame('[data-head]');
}
+ public function test_frame_stops_where_the_frame_is_missing(): void
+ {
+ $this->expectException(NotOneNode::class);
+ $this->expectExceptionMessage('(page): frame() needs exactly one match. The selector "iframe[data-here]" finds 0 nodes.');
+
+ Html::of(Page::HTML)->frame('iframe[data-here]');
+ }
+
public function test_it_reads_texts_raw_texts_and_attributes_in_the_order_of_the_page(): void
{
$page = Html::of(Page::HTML);
diff --git a/tests/Pest/ExpectationsTest.php b/tests/Pest/ExpectationsTest.php
index 0862b03..ebc5cf7 100644
--- a/tests/Pest/ExpectationsTest.php
+++ b/tests/Pest/ExpectationsTest.php
@@ -8,6 +8,8 @@
use PHPUnit\Framework\ExpectationFailedException;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Constraint\NotOneNode;
use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\Html;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NoMatch;
+use SorgeIt\PhpunitPestHtmlAssertions\PHPUnit\NotAPage;
use SorgeIt\PhpunitPestHtmlAssertions\Tests\Page;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Response;
@@ -42,32 +44,50 @@
'an empty node' => fn (Expectation $page): Expectation => $page->toBeEmptyNode('[data-empty]'),
]);
+dataset('failing expectations', [
+ 'no such node' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelector('[data-here]', $message),
+ 'another count' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorCount('[data-name]', 3, $message),
+ 'too few' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorCountAtLeast('[data-name]', 3, $message),
+ 'a part not in the text' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorTextContaining('h1', 'Montag', $message),
+ 'another text' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorText('h1', 'Review', $message),
+ 'a text of no node' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveAnySelectorText('[data-name]', 'Clara', $message),
+ 'a part of no text' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveAnySelectorTextContaining('[data-name]', 'Cla', $message),
+ 'another attribute value' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorAttribute('[data-link]', 'href', '/in', $message),
+ 'a part not in the attribute' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorAttributeContaining('[data-link]', 'href', 'u=2', $message),
+ 'no attribute of that name' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorAttributeNamed('[data-head]', 'wire:poll', $message),
+ 'a missing class' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectorClass('[data-name="Ben"]', 'bg-blue-500', $message),
+ 'another text of the region' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveText('Review', $message),
+ 'a part not in the text of the page' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveTextContaining('alert(1)', $message),
+ 'a text once' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveTextCount('Review', 1, $message),
+ 'the other order' => fn (Expectation $page, string $message = ''): Expectation => $page->toAppearBefore('[data-body]', '[data-head]', $message),
+ 'another title' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveTitle('Another page', $message),
+ 'another value' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveInputValue('email', 'ben@example.test', $message),
+ 'an unchecked box' => fn (Expectation $page, string $message = ''): Expectation => $page->toBeChecked('input[name="email"]', $message),
+ 'another option' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveSelectedOption('[data-day]', 'mo', $message),
+ 'an enabled button' => fn (Expectation $page, string $message = ''): Expectation => $page->toBeDisabled('[data-cancel]', $message),
+ 'a link to elsewhere' => fn (Expectation $page, string $message = ''): Expectation => $page->toHaveLink('Next', '/in', $message),
+ 'a node with text' => fn (Expectation $page, string $message = ''): Expectation => $page->toBeEmptyNode('h1', $message),
+]);
+
it('fails where the page does not', function (Closure $check): void {
expect(fn (): mixed => $check(expect(Page::HTML)))->toThrow(ExpectationFailedException::class);
-})->with([
- 'no such node' => fn (Expectation $page): Expectation => $page->toHaveSelector('[data-here]'),
- 'a node that is there' => fn (Expectation $page): Expectation => $page->not->toHaveSelector('[data-people]'),
- 'another count' => fn (Expectation $page): Expectation => $page->toHaveSelectorCount('[data-name]', 3),
- 'too few' => fn (Expectation $page): Expectation => $page->toHaveSelectorCountAtLeast('[data-name]', 3),
- 'a part not in the text' => fn (Expectation $page): Expectation => $page->toHaveSelectorTextContaining('h1', 'Montag'),
- 'a text of no node' => fn (Expectation $page): Expectation => $page->toHaveAnySelectorText('[data-name]', 'Clara'),
- 'a part of no text' => fn (Expectation $page): Expectation => $page->toHaveAnySelectorTextContaining('[data-name]', 'Cla'),
- 'another attribute value' => fn (Expectation $page): Expectation => $page->toHaveSelectorAttribute('[data-link]', 'href', '/in'),
- 'a part not in the attribute' => fn (Expectation $page): Expectation => $page->toHaveSelectorAttributeContaining('[data-link]', 'href', 'u=2'),
- 'no attribute of that name' => fn (Expectation $page): Expectation => $page->toHaveSelectorAttributeNamed('[data-head]', 'wire:poll'),
- 'a missing class' => fn (Expectation $page): Expectation => $page->toHaveSelectorClass('[data-name="Ben"]', 'bg-blue-500'),
- 'another text of the region' => fn (Expectation $page): Expectation => $page->toHaveText('Review'),
- 'a part not in the text of the page' => fn (Expectation $page): Expectation => $page->toHaveTextContaining('alert(1)'),
- 'a text once' => fn (Expectation $page): Expectation => $page->toHaveTextCount('Review', 1),
- 'the other order' => fn (Expectation $page): Expectation => $page->toAppearBefore('[data-body]', '[data-head]'),
- 'another title' => fn (Expectation $page): Expectation => $page->toHaveTitle('Another page'),
- 'another value' => fn (Expectation $page): Expectation => $page->toHaveInputValue('email', 'ben@example.test'),
- 'an unchecked box' => fn (Expectation $page): Expectation => $page->toBeChecked('input[name="email"]'),
- 'another option' => fn (Expectation $page): Expectation => $page->toHaveSelectedOption('[data-day]', 'mo'),
- 'an enabled button' => fn (Expectation $page): Expectation => $page->toBeDisabled('[data-cancel]'),
- 'a link to elsewhere' => fn (Expectation $page): Expectation => $page->toHaveLink('Next', '/in'),
- 'a node with text' => fn (Expectation $page): Expectation => $page->toBeEmptyNode('h1'),
-]);
+})->with('failing expectations');
+
+it('fails where a node is there that a check turned around asks to miss', function (): void {
+ expect(fn (): mixed => expect(Page::HTML)->not->toHaveSelector('[data-people]'))->toThrow(ExpectationFailedException::class);
+});
+
+it('shows the message of the test before its own', function (Closure $check): void {
+ try {
+ $check(expect(Page::HTML), 'The cart shows what the customer chose.');
+ } catch (ExpectationFailedException $expectationFailedException) {
+ expect($expectationFailedException->getMessage())->toStartWith("The cart shows what the customer chose.\nFailed asserting that (page");
+
+ return;
+ }
+
+ $this->fail('The check passed.');
+})->with('failing expectations');
it('reads a string, a crawler, a region, a test response and a PSR-7 response', function (mixed $page): void {
expect($page)->toHaveSelectorCount('[data-name]', 2);
@@ -92,10 +112,15 @@
->toThrow(ExpectationFailedException::class, '(page) > [data-people] has a node matching "h1"');
});
-it('fails within a region that is missing, so a check turned around after it cannot pass on nothing', function (): void {
- expect(fn (): mixed => expect(html(Page::HTML))->within('[data-here]')->not->toHaveSelector('a'))
- ->toThrow(ExpectationFailedException::class, 'has 1 nodes matching "[data-here]"');
-});
+it('stops at a region that is missing, also turned around, so no check after it can pass on nothing', function (Closure $check, string $exception, string $text): void {
+ expect(fn (): mixed => $check(expect(html(Page::HTML))))->toThrow($exception, $text);
+})->with([
+ 'within' => [fn (Expectation $page): mixed => $page->within('[data-here]')->not->toHaveSelector('a'), NotOneNode::class, '(page): within() needs exactly one match. The selector "[data-here]" finds 0 nodes.'],
+ 'within, turned around' => [fn (Expectation $page): mixed => $page->not->within('[data-here]'), NotOneNode::class, 'within() needs exactly one match.'],
+ 'frame, turned around' => [fn (Expectation $page): mixed => $page->not->frame('iframe[data-here]'), NotOneNode::class, 'frame() needs exactly one match.'],
+ 'a frame without srcdoc, turned around' => [fn (Expectation $page): mixed => $page->not->frame('[data-head]'), NotAPage::class, 'has no srcdoc, so it holds no page.'],
+ 'eachMatch, turned around' => [fn (Expectation $page): mixed => $page->not->eachMatch('[data-here]', fn (): null => null), LogicException::class, 'eachMatch() cannot be turned around'],
+]);
it('fails a check of one node on none or two, also turned around', function (Closure $check): void {
expect(fn (): mixed => $check(expect(Page::HTML)))->toThrow(NotOneNode::class, 'a check of one node needs exactly one match.');
@@ -109,7 +134,27 @@
expect(html(Page::HTML))->frame('[data-mail]')->toHaveSelectorText('[data-mail-text]', 'Hello');
});
-it('runs the same checks on every match, and fails where nothing matches', function (): void {
+it('refuses eachMatch turned around, which would pass where one match fails', function (): void {
+ expect(fn (): mixed => expect(Page::HTML)->not->eachMatch('[data-name]', fn (Expectation $name): Expectation => $name->toHaveSelectorClass(':scope', 'bg-blue-500')))
+ ->toThrow(LogicException::class, 'eachMatch() cannot be turned around: ->not would pass where one match fails.')
+ ->and(fn (): mixed => expect(html(Page::HTML))->within('[data-people]')->not->eachMatch('li', fn (): null => null))
+ ->toThrow(LogicException::class, 'eachMatch() cannot be turned around');
+});
+
+it('runs eachMatch where a test turns around something else around it', function (Closure $check): void {
+ expect($check)->not->toThrow(LogicException::class);
+})->with([
+ // Pest hands a closure to a parameter of the type Closure as it is, without calling it.
+ 'a closure of the test' => [fn (): Expectation => expect(Page::HTML)->eachMatch('[data-name]', fn (Expectation $name): Expectation => $name->toHaveSelectorClass(':scope', 'rounded-lg'))],
+ 'a function of the test' => [eachMatchOnEveryName(...)],
+]);
+
+function eachMatchOnEveryName(): Expectation
+{
+ return expect(Page::HTML)->eachMatch('[data-name]', fn (Expectation $name): Expectation => $name->toHaveSelectorClass(':scope', 'rounded-lg'));
+}
+
+it('runs the same checks on every match, and stops where nothing matches', function (): void {
$seen = [];
expect(Page::HTML)->eachMatch('[data-name]', function (Expectation $name, int $index) use (&$seen): void {
@@ -119,7 +164,7 @@
expect($seen)->toBe([0, 1])
->and(fn (): Expectation => expect(Page::HTML)->eachMatch('[data-here]', fn (): null => null))
- ->toThrow(ExpectationFailedException::class, 'has a node matching "[data-here]"');
+ ->toThrow(NoMatch::class, '(page): eachMatch() needs at least one match. The selector "[data-here]" finds 0 nodes.');
});
it('reads texts, raw texts and attributes as lists that Pest checks further', function (): void {
@@ -137,3 +182,68 @@
->toContain('(page) > [data-people]')
->toContain('Anna Example');
});
+
+it('takes the message by name after an optional value', function (): void {
+ expect(fn (): mixed => expect(Page::HTML)->toHaveSelectorAttribute('[data-cancel]', 'disabled', message: 'Cancel stays open.'))
+ ->toThrow(ExpectationFailedException::class, "Cancel stays open.\nFailed asserting that (page) has one node matching \"[data-cancel]\" with the attribute \"disabled\"");
+});
+
+it('shows the message of the test before a check of one node that finds two, also turned around', function (Closure $check): void {
+ try {
+ $check(expect(Page::HTML));
+ } catch (NotOneNode $notOneNode) {
+ expect($notOneNode->getMessage())->toStartWith("The list names one person.\n(page): a check of one node needs exactly one match.");
+
+ return;
+ }
+
+ $this->fail('The check passed on two nodes.');
+})->with([
+ 'the check' => fn (Expectation $page): Expectation => $page->toHaveSelectorText('[data-name]', 'Anna Example', 'The list names one person.'),
+ 'turned around' => fn (Expectation $page): Expectation => $page->not->toHaveSelectorText('[data-name]', 'Clara', 'The list names one person.'),
+]);
+
+it('shows the message of the test where eachMatch finds nothing or reads no page', function (): void {
+ expect(fn (): mixed => expect(Page::HTML)->eachMatch('[data-here]', fn (): null => null, 'Each person has an avatar.'))
+ ->toThrow(NoMatch::class, "Each person has an avatar.\n(page): eachMatch() needs at least one match.")
+ ->and(fn (): mixed => expect(42)->eachMatch('p', fn (): null => null, 'Each person has an avatar.'))
+ ->toThrow(NotAPage::class, "Each person has an avatar.\nA check of HTML reads ");
+});
+
+it('stops a check turned around on a value that is not a page, so it cannot pass', function (): void {
+ expect(fn (): mixed => expect(['errors' => []])->not->toHaveSelector('[data-errors]'))
+ ->toThrow(NotAPage::class, 'A check of HTML reads ');
+});
+
+it('keeps the text of a failure without a message', function (): void {
+ try {
+ // A whole page: the parsers of Symfony 7.4 and 8.1 add a missing head differently.
+ expect('')->toHaveSelectorCount('li', 2);
+ } catch (ExpectationFailedException $expectationFailedException) {
+ expect($expectationFailedException->getMessage())
+ ->toBe("Failed asserting that (page) has 2 nodes matching \"li\".\nThe selector \"li\" finds 1 nodes.\n\nIn (page):\n \n \n \n
\n - \n a");
+
+ return;
+ }
+
+ $this->fail('The check passed.');
+});
+
+// Pest builds the message of `->not` itself: the message of the test is its last argument, without the region.
+it('shows the message of the test among the arguments of a check turned around', function (Closure $check, string $text): void {
+ expect(fn (): mixed => $check(expect(Page::HTML)))->toThrow(ExpectationFailedException::class, $text);
+})->with([
+ 'by position' => [
+ fn (Expectation $page): Expectation => $page->not->toHaveSelector('[data-people]', 'The cart is empty after checkout.'),
+ "not to have selector '[data-people]' 'The cart is empty after checkout.'.",
+ ],
+ 'by name' => [
+ fn (Expectation $page): Expectation => $page->not->toHaveSelectorAttribute('[data-agree]', 'checked', message: 'The box starts empty.'),
+ "not to have selector attribute '[data-agree]' 'checked' 'The box starts empty.'.",
+ ],
+]);
+
+it('shows the message and the region where a count of zero says that a node is missing', function (): void {
+ expect(fn (): mixed => expect(Page::HTML)->toHaveSelectorCount('[data-people]', 0, 'The cart is empty after checkout.'))
+ ->toThrow(ExpectationFailedException::class, "The cart is empty after checkout.\nFailed asserting that (page) has 0 nodes matching \"[data-people]\".");
+});