Skip to content

Add assert in test live component #2712

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: 2.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/LiveComponent/src/Test/InteractsWithLiveComponents.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
32 changes: 32 additions & 0 deletions src/LiveComponent/src/Test/TestLiveComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,36 @@ private function flattenFormValues(array $values, string $prefix = ''): array

return $result;
}

/**
* @return ?array{data: array<string, string>, 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<int, array{data: array<string, string>, 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);
}
}
Loading