From c994d18b259525a6af5c428211c6d4d4ff290cf0 Mon Sep 17 00:00:00 2001 From: Arkalo2 <24898676+Arkalo2@users.noreply.github.com> Date: Mon, 5 May 2025 14:39:18 +0200 Subject: [PATCH] Add assert in test live component --- .../src/Test/InteractsWithLiveComponents.php | 20 ++++++++++++ .../src/Test/TestLiveComponent.php | 32 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/LiveComponent/src/Test/InteractsWithLiveComponents.php b/src/LiveComponent/src/Test/InteractsWithLiveComponents.php index 377fbad1f34..a3d6418491e 100644 --- a/src/LiveComponent/src/Test/InteractsWithLiveComponents.php +++ b/src/LiveComponent/src/Test/InteractsWithLiveComponents.php @@ -44,4 +44,24 @@ protected function createLiveComponent(string $name, array $data = [], ?KernelBr self::getContainer()->get('router'), ); } + + protected function assertComponentEmitEvent(TestLiveComponent $testLiveComponent, string $eventName, ?array $parameters = null): void + { + $eventData = $testLiveComponent->getEmittedEvent($testLiveComponent->render(), $eventName); + + $this->assertNotNull($eventData, \sprintf('Event %s not emitted', $eventName)); + + if (null === $parameters) { + return; + } + + foreach ($parameters as $key => $value) { + $this->assertSame($value, $eventData['data'][$key], \sprintf('EventData (%s) is not valid', $key)); + } + } + + protected function assertComponentNotEmitEvent(TestLiveComponent $testLiveComponent, string $eventName): void + { + $this->assertNull($this->testLiveComponent($testLiveComponent->render(), $eventName), \sprintf('Event %s emitted', $eventName)); + } } diff --git a/src/LiveComponent/src/Test/TestLiveComponent.php b/src/LiveComponent/src/Test/TestLiveComponent.php index 0e587a38256..54a9ece127f 100644 --- a/src/LiveComponent/src/Test/TestLiveComponent.php +++ b/src/LiveComponent/src/Test/TestLiveComponent.php @@ -229,4 +229,36 @@ private function flattenFormValues(array $values, string $prefix = ''): array return $result; } + + /** + * @return ?array{data: array, event: string} + */ + public function getEmittedEvent(RenderedComponent $render, string $eventName): ?array + { + $eventsData = $this->getEmittedEvents($render); + + foreach ($eventsData as $eventData) { + if ($eventData['event'] === $eventName) { + return $eventData; + } + } + + return null; + } + + /** + * @return array, event: string}> + */ + public function getEmittedEvents(RenderedComponent $render): array + { + $div = $render->crawler()->filter('div'); + + $emit = $div->attr('data-live-events-to-emit-value'); + + if (null === $emit) { + return []; + } + + return \json_decode($emit, true); + } }