Skip to content

[LiveComponent] 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

Open
wants to merge 15 commits into
base: 2.x
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions src/LiveComponent/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3781,6 +3781,12 @@ uses Symfony's test client to render and make requests to your components::
->emit('increaseEvent', ['amount' => 2]) // emit a live event with arguments
;

// Assert that the event was emitted
$this->componentHasEmittedEvent($testComponent->render(), 'increaseEvent')
->withData(['amount' => 2])
->withDataSubset(['amount' => 2]) // test partial parameters
;

// set live props
$testComponent
->set('count', 99)
Expand Down
52 changes: 52 additions & 0 deletions src/LiveComponent/src/Test/InteractsWithLiveComponents.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,56 @@ protected function createLiveComponent(string $name, array $data = [], ?KernelBr
self::getContainer()->get('router'),
);
}

/**
* @return object{withData: callable(array): void, withDataSubset: callable(array): object}
*/
protected function assertComponentEmitEvent(TestLiveComponent $testLiveComponent, string $expectedEventName): object
{
$event = $testLiveComponent->getEmittedEvent($testLiveComponent->render(), $expectedEventName);

$this->assertNotNull($event, \sprintf('The component "%s" did not emit event "%s".', $testLiveComponent->getName(), $expectedEventName));

return new class($this, $event['event'], $event['data']) {
/**
* @param array<string, int|float|string|bool|null> $data
*/
public function __construct(private KernelTestCase $parent, private readonly string $eventName, private readonly array $data)
{
}

/**
* @return self
*/
public function withDataSubset(array $expectedEventData): object
{
foreach ($expectedEventData as $key => $value) {
$this->parent->assertArrayHasKey($key, $this->data, \sprintf('The expected event "%s" data "%s" does not exists', $this->eventName, $key));
$this->parent->assertSame(
$value,
$this->data[$key],
\sprintf(
'The expected event "%s" data "%s" expected "%s" but "%s" given',
$this->eventName,
$key,
$value,
$this->data[$key]
)
);
}

return $this;
}

public function withData(array $expectedEventData): void
{
$this->parent->assertEquals($expectedEventData, $this->data, \sprintf('The expected event "%s" data does not match.', $this->eventName));
}
};
}

protected function assertComponentNotEmitEvent(TestLiveComponent $testLiveComponent, string $eventName): void
{
$this->assertNull($testLiveComponent->getEmittedEvent($testLiveComponent->render(), $eventName), \sprintf('The component "%s" did not emit event "%s".', $testLiveComponent->getName(), $eventName));
}
}
35 changes: 35 additions & 0 deletions src/LiveComponent/src/Test/TestLiveComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,39 @@ private function flattenFormValues(array $values, string $prefix = ''): array

return $result;
}

/**
* @return ?array{data: array<string, int|float|string|bool|null>, event: non-empty-string}
*/
public function getEmittedEvent(RenderedComponent $render, string $eventName): ?array
{
$events = $this->getEmittedEvents($render);

foreach ($events as $event) {
if ($event['event'] === $eventName) {
return $event;
}
}

return null;
}

/**
* @return array<array{data: array<string, int|float|string|bool|null>, event: non-empty-string}>
*/
public function getEmittedEvents(RenderedComponent $render): array
{
$emit = $render->crawler()->filter('[data-live-name-value]')->attr('data-live-events-to-emit-value');

if (null === $emit) {
return [];
}

return json_decode($emit, associative: true, flags: \JSON_THROW_ON_ERROR);
}

public function getName(): string
{
return $this->metadata->getName();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ final class ComponentWithEmit
#[LiveAction]
public function actionThatEmits(): void
{
$this->emit('event1', ['foo' => 'bar']);
$this->emit('event1', ['foo' => 'bar', 'bar' => 'foo']);
$this->events = $this->liveResponder->getEventsToEmit();
}

Expand Down
2 changes: 1 addition & 1 deletion src/LiveComponent/tests/Functional/LiveResponderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function testComponentCanEmitEvents(): void
])
->assertSuccessful()
->assertSee('Event: event1')
->assertSee('Data: {"foo":"bar"}');
->assertSee('Data: {"foo":"bar","bar":"foo"}');
}

public function testComponentCanDispatchBrowserEvents(): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\UX\LiveComponent\Tests\Functional\Test;

use PHPUnit\Framework\AssertionFailedError;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\InMemoryUser;
Expand Down Expand Up @@ -217,4 +218,75 @@ public function testSetLocaleRenderLocalizedComponent(): void
$testComponent->setRouteLocale('de');
$this->assertStringContainsString('Locale: de', $testComponent->render());
}

public function testComponentEmitsExpectedEventData(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->assertComponentEmitEvent($testComponent, 'event1')->withData([
'foo' => 'bar',
'bar' => 'foo',
]);
}

public function testComponentEmitsExpectedEventDataFails(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('The expected event "event1" data does not match');
$this->assertComponentEmitEvent($testComponent, 'event1')->withData([
'foo' => 'bar',
]);
}

public function testComponentEmitsExpectedPartialEventData(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->assertComponentEmitEvent($testComponent, 'event1')
->withDataSubset(['foo' => 'bar'])
->withDataSubset(['bar' => 'foo'])
;
}

public function testComponentDoesNotEmitUnexpectedEvent(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->assertComponentNotEmitEvent($testComponent, 'event2');
}

public function testComponentDoesNotEmitUnexpectedEventFails(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('The component "component_with_emit" did not emit event "event1".');
$this->assertComponentNotEmitEvent($testComponent, 'event1');
}

public function testComponentEmitsEventWithIncorrectDataFails(): void
{
$testComponent = $this->createLiveComponent('component_with_emit');

$testComponent->call('actionThatEmits');

$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('The expected event "event1" data does not match.');
$this->assertComponentEmitEvent($testComponent, 'event1')->withData([
'foo' => 'bar',
'foo2' => 'bar2',
]);
}
}