3 use \Illuminate\Foundation\Testing\TestResponse as BaseTestResponse;
4 use Symfony\Component\DomCrawler\Crawler;
5 use PHPUnit\Framework\Assert as PHPUnit;
9 * Custom extension of the default Laravel TestResponse class.
12 class TestResponse extends BaseTestResponse {
14 protected $crawlerInstance;
17 * Get the DOM Crawler for the response content.
20 protected function crawler()
22 if (!is_object($this->crawlerInstance)) {
23 $this->crawlerInstance = new Crawler($this->getContent());
25 return $this->crawlerInstance;
29 * Assert the response contains the specified element.
30 * @param string $selector
33 public function assertElementExists(string $selector)
35 $elements = $this->crawler()->filter($selector);
37 $elements->count() > 0,
38 'Unable to find element matching the selector: '.PHP_EOL.PHP_EOL.
39 "[{$selector}]".PHP_EOL.PHP_EOL.
40 'within'.PHP_EOL.PHP_EOL.
41 "[{$this->getContent()}]."
47 * Assert the response does not contain the specified element.
48 * @param string $selector
51 public function assertElementNotExists(string $selector)
53 $elements = $this->crawler()->filter($selector);
55 $elements->count() === 0,
56 'Found elements matching the selector: '.PHP_EOL.PHP_EOL.
57 "[{$selector}]".PHP_EOL.PHP_EOL.
58 'within'.PHP_EOL.PHP_EOL.
59 "[{$this->getContent()}]."
65 * Assert the response includes a specific element containing the given text.
66 * @param string $selector
70 public function assertElementContains(string $selector, string $text)
72 $elements = $this->crawler()->filter($selector);
74 $pattern = $this->getEscapedPattern($text);
75 foreach ($elements as $element) {
76 $element = new Crawler($element);
77 if (preg_match("/$pattern/i", $element->html())) {
85 'Unable to find element of selector: '.PHP_EOL.PHP_EOL.
86 "[{$selector}]".PHP_EOL.PHP_EOL.
87 'containing text'.PHP_EOL.PHP_EOL.
88 "[{$text}]".PHP_EOL.PHP_EOL.
89 'within'.PHP_EOL.PHP_EOL.
90 "[{$this->getContent()}]."
97 * Assert the response does not include a specific element containing the given text.
98 * @param string $selector
102 public function assertElementNotContains(string $selector, string $text)
104 $elements = $this->crawler()->filter($selector);
106 $pattern = $this->getEscapedPattern($text);
107 foreach ($elements as $element) {
108 $element = new Crawler($element);
109 if (preg_match("/$pattern/i", $element->html())) {
117 'Found element of selector: '.PHP_EOL.PHP_EOL.
118 "[{$selector}]".PHP_EOL.PHP_EOL.
119 'containing text'.PHP_EOL.PHP_EOL.
120 "[{$text}]".PHP_EOL.PHP_EOL.
121 'within'.PHP_EOL.PHP_EOL.
122 "[{$this->getContent()}]."
129 * Get the escaped text pattern for the constraint.
130 * @param string $text
133 protected function getEscapedPattern($text)
135 $rawPattern = preg_quote($text, '/');
136 $escapedPattern = preg_quote(e($text), '/');
137 return $rawPattern == $escapedPattern
138 ? $rawPattern : "({$rawPattern}|{$escapedPattern})";