Skip to content

Instantly share code, notes, and snippets.

@imliam
Created January 19, 2020 01:59
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/0a373d86dbf3d8706d057f184dd83cf3 to your computer and use it in GitHub Desktop.
Save imliam/0a373d86dbf3d8706d057f184dd83cf3 to your computer and use it in GitHub Desktop.

You can register the mixin class in the register method of a Laravel service provider:

use Illuminate\Foundation\Testing\TestResponse;

TestResponse::mixin(TestResponseMixin::class);
<?php
use DOMXPath;
use DOMDocument;
use DOMNodeList;
use Illuminate\Support\Str;
use Illuminate\Foundation\Testing\Assert as PHPUnit;
use Symfony\Component\CssSelector\CssSelectorConverter;
class TestResponseMixin
{
public function getSelectorContents()
{
return function (string $selector): DOMNodeList {
$dom = new DOMDocument();
@$dom->loadHTML(
mb_convert_encoding($this->getContent(), 'HTML-ENTITIES', 'UTF-8'),
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
);
$xpath = new DOMXPath($dom);
$converter = new CssSelectorConverter();
$xpathSelector = $converter->toXPath($selector);
$elements = $xpath->query($xpathSelector);
return $elements;
};
}
public function assertSelectorContains()
{
return function (string $selector, string $value) {
$selectorContents = $this->getSelectorContents($selector);
if (empty($selectorContents)) {
PHPUnit::fail("The selector '{$selector}' was not found in the response.");
}
foreach ($selectorContents as $element) {
if (Str::contains($element->textContent, $value)) {
PHPUnit::assertTrue(true);
return $this;
}
}
PHPUnit::fail("The selector '{$selector}' did not contain the value '{$value}'.");
return $this;
};
}
public function assertSelectorsAllContain()
{
return function (string $selector, string $value) {
$selectorContents = $this->getSelectorContents($selector);
if (empty($selectorContents)) {
PHPUnit::fail("The selector '{$selector}' was not found in the response.");
}
foreach ($selectorContents as $element) {
if (!Str::contains($element->textContent, $value)) {
PHPUnit::fail("The selector '{$selector}' did not contain the value '{$value}'.");
return $this;
}
}
PHPUnit::assertTrue(true);
return $this;
};
}
public function assertSelectorAttributeEquals()
{
return function (string $selector, string $attribute, $expected) {
$nodes = $this->getSelectorContents($selector);
if (count($nodes) === 0) {
PHPUnit::fail("The selector '{$selector} was not found in the response.");
return $this;
}
$firstNode = $nodes[0];
PHPUnit::assertEquals($expected, $firstNode->getAttribute($attribute));
return $this;
};
}
}
@jeffochoa
Copy link

This is awesome. @imliam it would be great to have this available as a package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment