Skip to content

Commit a43398b

Browse files
committed
Add assert in test live component
1 parent bb13764 commit a43398b

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/LiveComponent/src/Test/InteractsWithLiveComponents.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,24 @@ protected function createLiveComponent(string $name, array $data = [], ?KernelBr
4444
self::getContainer()->get('router'),
4545
);
4646
}
47+
48+
protected function assertComponentEmitEvent(TestLiveComponent $testLiveComponent, string $eventName, ?array $parameters = null): void
49+
{
50+
$eventData = $testLiveComponent->getEmittedEvent($testLiveComponent->render(), $eventName);
51+
52+
$this->assertNotNull($eventData, \sprintf('Event %s not emitted', $eventName));
53+
54+
if (null === $parameters) {
55+
return;
56+
}
57+
58+
foreach ($parameters as $key => $value) {
59+
$this->assertSame($value, $eventData['data'][$key], \sprintf('EventData (%s) is not valid', $key));
60+
}
61+
}
62+
63+
protected function assertComponentNotEmitEvent(TestLiveComponent $testLiveComponent, string $eventName): void
64+
{
65+
$this->assertNull($this->testLiveComponent($testLiveComponent->render(), $eventName), \sprintf('Event %s emitted', $eventName));
66+
}
4767
}

src/LiveComponent/src/Test/TestLiveComponent.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,4 +229,36 @@ private function flattenFormValues(array $values, string $prefix = ''): array
229229

230230
return $result;
231231
}
232+
233+
/**
234+
* @return ?array{data: array<string, string>, event: string}
235+
*/
236+
public function getEmittedEvent(RenderedComponent $render, string $eventName): ?array
237+
{
238+
$eventsData = $this->getEmittedEvents($render);
239+
240+
foreach ($eventsData as $eventData) {
241+
if ($eventData['event'] === $eventName) {
242+
return $eventData;
243+
}
244+
}
245+
246+
return null;
247+
}
248+
249+
/**
250+
* @return array<int, array{data: array<string, string>, event: string}>
251+
*/
252+
public function getEmittedEvents(RenderedComponent $render): array
253+
{
254+
$div = $render->crawler()->filter('div');
255+
256+
$emit = $div->attr('data-live-events-to-emit-value');
257+
258+
if (null === $emit) {
259+
return [];
260+
}
261+
262+
return \json_decode($emit, true);
263+
}
232264
}

0 commit comments

Comments
 (0)