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.
19 protected function crawler(): Crawler
21 if (!is_object($this->crawlerInstance)) {
22 $this->crawlerInstance = new Crawler($this->getContent());
24 return $this->crawlerInstance;
28 * Assert the response contains the specified element.
31 public function assertElementExists(string $selector)
33 $elements = $this->crawler()->filter($selector);
35 $elements->count() > 0,
36 'Unable to find element matching the selector: '.PHP_EOL.PHP_EOL.
37 "[{$selector}]".PHP_EOL.PHP_EOL.
38 'within'.PHP_EOL.PHP_EOL.
39 "[{$this->getContent()}]."
45 * Assert the response does not contain the specified element.
48 public function assertElementNotExists(string $selector)
50 $elements = $this->crawler()->filter($selector);
52 $elements->count() === 0,
53 'Found elements matching the selector: '.PHP_EOL.PHP_EOL.
54 "[{$selector}]".PHP_EOL.PHP_EOL.
55 'within'.PHP_EOL.PHP_EOL.
56 "[{$this->getContent()}]."
62 * Assert the response includes a specific element containing the given text.
65 public function assertElementContains(string $selector, string $text)
67 $elements = $this->crawler()->filter($selector);
69 $pattern = $this->getEscapedPattern($text);
70 foreach ($elements as $element) {
71 $element = new Crawler($element);
72 if (preg_match("/$pattern/i", $element->html())) {
80 'Unable to find element of selector: '.PHP_EOL.PHP_EOL.
81 "[{$selector}]".PHP_EOL.PHP_EOL.
82 'containing text'.PHP_EOL.PHP_EOL.
83 "[{$text}]".PHP_EOL.PHP_EOL.
84 'within'.PHP_EOL.PHP_EOL.
85 "[{$this->getContent()}]."
92 * Assert the response does not include a specific element containing the given text.
95 public function assertElementNotContains(string $selector, string $text)
97 $elements = $this->crawler()->filter($selector);
99 $pattern = $this->getEscapedPattern($text);
100 foreach ($elements as $element) {
101 $element = new Crawler($element);
102 if (preg_match("/$pattern/i", $element->html())) {
110 'Found element of selector: '.PHP_EOL.PHP_EOL.
111 "[{$selector}]".PHP_EOL.PHP_EOL.
112 'containing text'.PHP_EOL.PHP_EOL.
113 "[{$text}]".PHP_EOL.PHP_EOL.
114 'within'.PHP_EOL.PHP_EOL.
115 "[{$this->getContent()}]."
122 * Assert there's a notification within the view containing the given text.
125 public function assertNotificationContains(string $text)
127 return $this->assertElementContains('[notification]', $text);
131 * Get the escaped text pattern for the constraint.
134 protected function getEscapedPattern(string $text)
136 $rawPattern = preg_quote($text, '/');
137 $escapedPattern = preg_quote(e($text), '/');
138 return $rawPattern == $escapedPattern
139 ? $rawPattern : "({$rawPattern}|{$escapedPattern})";