|
5 | 5 | namespace Sinnbeck\DomAssertions; |
6 | 6 |
|
7 | 7 | use Closure; |
| 8 | +use DOMElement; |
8 | 9 | use DOMException; |
9 | 10 | use Illuminate\Testing\TestResponse; |
10 | 11 | use PHPUnit\Framework\Assert; |
@@ -85,6 +86,74 @@ public function assertElementExists(): Closure |
85 | 86 | }; |
86 | 87 | } |
87 | 88 |
|
| 89 | + public function assertContainsElement(): Closure |
| 90 | + { |
| 91 | + return function (string $selector, array $attributes = []): TestResponse { |
| 92 | + /** @var TestResponse $this */ |
| 93 | + Assert::assertNotEmpty( |
| 94 | + (string) $this->getContent(), |
| 95 | + 'The response is empty!' |
| 96 | + ); |
| 97 | + |
| 98 | + try { |
| 99 | + $parser = DomParser::new($this->getContent()); |
| 100 | + } catch (DOMException $exception) { |
| 101 | + Assert::fail($exception->getMessage()); |
| 102 | + } |
| 103 | + |
| 104 | + $element = $parser->query($selector); |
| 105 | + |
| 106 | + Assert::assertNotNull( |
| 107 | + $element, |
| 108 | + sprintf('No element found with selector: %s', $selector) |
| 109 | + ); |
| 110 | + |
| 111 | + if (! $element instanceof DOMElement) { |
| 112 | + Assert::fail('The element found is not a DOMElement!'); |
| 113 | + } |
| 114 | + |
| 115 | + foreach ($attributes as $attribute => $expected) { |
| 116 | + switch ($attribute) { |
| 117 | + case 'text': |
| 118 | + $actual = trim($element->textContent); |
| 119 | + Assert::assertStringContainsString( |
| 120 | + $expected, |
| 121 | + $actual, |
| 122 | + sprintf( |
| 123 | + 'Failed asserting that element [%s] text contains "%s". Actual: "%s".', |
| 124 | + $selector, |
| 125 | + $expected, |
| 126 | + $actual |
| 127 | + ) |
| 128 | + ); |
| 129 | + break; |
| 130 | + |
| 131 | + default: |
| 132 | + $actual = $element->getAttribute($attribute); |
| 133 | + Assert::assertNotEmpty( |
| 134 | + $actual, |
| 135 | + sprintf('Attribute [%s] not found in element [%s].', $attribute, $selector) |
| 136 | + ); |
| 137 | + |
| 138 | + Assert::assertStringContainsString( |
| 139 | + $expected, |
| 140 | + $actual, |
| 141 | + sprintf( |
| 142 | + 'Failed asserting that attribute [%s] of element [%s] contains "%s". Actual: "%s".', |
| 143 | + $attribute, |
| 144 | + $selector, |
| 145 | + $expected, |
| 146 | + $actual |
| 147 | + ) |
| 148 | + ); |
| 149 | + break; |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return $this; |
| 154 | + }; |
| 155 | + } |
| 156 | + |
88 | 157 | public function assertForm(): Closure |
89 | 158 | { |
90 | 159 | return $this->assertFormExists(); |
|
0 commit comments