Skip to content
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

[6.x] Add Testing assertions for actions (javascript render) #1701

Merged
merged 3 commits into from
Sep 27, 2024
Merged
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
9 changes: 6 additions & 3 deletions src/Providers/PowerGridServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@
use Illuminate\Support\Facades\{Blade, Event};
use Illuminate\Support\{ServiceProvider};
use Livewire\Features\SupportLegacyModels\{EloquentCollectionSynth, EloquentModelSynth};
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use PowerComponents\LivewirePowerGrid\Commands\{CreateCommand, PublishCommand, UpdateCommand};
use PowerComponents\LivewirePowerGrid\Components\Filters\FilterManager;
use PowerComponents\LivewirePowerGrid\Components\Rules\RuleManager;
use PowerComponents\LivewirePowerGrid\Support\PowerGridTableCache;
use PowerComponents\LivewirePowerGrid\{
Livewire\LazyChild,
use PowerComponents\LivewirePowerGrid\{Livewire\LazyChild,
Livewire\PerformanceCard,
PowerGridManager};
PowerGridManager,
Testing\TestActions};

/** @codeCoverageIgnore */
class PowerGridServiceProvider extends ServiceProvider
Expand All @@ -35,6 +36,8 @@ public function boot(): void

Livewire::propertySynthesizer(EloquentModelSynth::class);
Livewire::propertySynthesizer(EloquentCollectionSynth::class);

Testable::mixin(new TestActions());
}

public function register(): void
Expand Down
80 changes: 80 additions & 0 deletions src/Testing/TestActions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace PowerComponents\LivewirePowerGrid\Testing;

use Closure;

use PHPUnit\Framework\Assert;
use PowerComponents\LivewirePowerGrid\DataSource\Processors\DataSourceBase;

class TestActions
{
public function assertHasAction(): Closure
{
return function (string $action): static {
$actionFound = collect(DataSourceBase::$actionsHtml)
->flatten(1)
->contains(fn (array $dishAction): bool => $dishAction['action'] === $action);

Assert::assertTrue($actionFound, "Failed asserting that the action '$action' exists in the table.");

return $this;
};
}

public function assertActionHasIcon(): Closure
{
return function (string $action, string $icon, ?string $iconClass = null): static {
/** @var array $actionFound */
$actionFound = collect(DataSourceBase::$actionsHtml)
->flatten(1)
->first(function ($dishAction) use ($action, $icon) {
/** @var array $dishAction */
return $dishAction['action'] === $action && $dishAction['icon'] === $icon;
});

Assert::assertNotNull($actionFound, "Failed asserting that the action '$action' has the icon '$icon'.");

if ($iconClass !== null) {
$iconClassFound = isset($actionFound['iconAttributes']['class']) && str_contains($actionFound['iconAttributes']['class'], $iconClass);
Assert::assertTrue($iconClassFound, "Failed asserting that the icon of action '$action' contains the class '$iconClass'.");
}

return $this;
};
}

public function assertActionContainsAttribute(): Closure
{
return function (string $action, string $attribute, string $expected, array $expectedParams = []): static {
$attributeFound = collect(DataSourceBase::$actionsHtml)
->flatten(1)
->first(function ($dishAction) use ($action, $attribute, $expected, $expectedParams) {
/** @var array $dishAction */
if ($dishAction['action'] === $action && isset($dishAction['attributes'][$attribute])) {
$attributeValue = $dishAction['attributes'][$attribute];

if (str_contains($attributeValue, 'JSON.parse')) {
preg_match("/JSON\.parse\('(.*)'\)/", $attributeValue, $matches);
$jsonEscaped = $matches[1] ?? null;

if ($jsonEscaped) {
$jsonStringClean = strval(json_decode('"' . $jsonEscaped . '"', true));
$data = json_decode($jsonStringClean, true);

return $data == $expectedParams;
}
}

return str_contains($attributeValue, $expected);
}

return false;
});

Assert::assertNotNull($attributeFound, "Failed asserting that the '$attribute' of action '$action' contains the expected parameters.");

return $this;
};
}
}
132 changes: 132 additions & 0 deletions tests/Feature/Testing/TestActionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

use Illuminate\Support\{Carbon, Collection, Number};
use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;

use function PowerComponents\LivewirePowerGrid\Tests\Plugins\livewire;

use PowerComponents\LivewirePowerGrid\Themes\{Bootstrap5, Tailwind};
use PowerComponents\LivewirePowerGrid\{Button, Column, PowerGridComponent, PowerGridFields};

$component = new class () extends PowerGridComponent {
public string $tableName = 'datasource-collection-table';

public function setUp(): array
{
return [
PowerGrid::header()
->showToggleColumns()
->showSearchInput(),

PowerGrid::footer()
->showPerPage()
->showRecordCount(),
];
}

public function datasource(): Collection
{
return collect([
[
'id' => 29,
'name' => 'Luan',
'balance' => 241.86,
'is_online' => true,
'created_at' => '2023-01-01 00:00:00',
],
[
'id' => 57,
'name' => 'Daniel',
'balance' => 166.51,
'is_online' => true,
'created_at' => '2023-02-02 00:00:00',
],
[
'id' => 93,
'name' => 'Claudio',
'balance' => 219.01,
'is_online' => false,
'created_at' => '2023-03-03 00:00:00',
],
[
'id' => 104,
'name' => 'Vitor',
'balance' => 44.28,
'is_online' => true,
'created_at' => '2023-04-04 00:00:00',
],
]);
}

public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name')
->add('balance', fn ($item) => Number::currency($item->balance, in: 'BRL', locale: 'pt-BR'))
->add('is_online', fn ($item) => $item->is_online ? '✅' : '❌')
->add('created_at', fn ($item) => Carbon::parse($item->created_at))
->add('created_at_formatted', fn ($item) => Carbon::parse($item->created_at)->format('d/m/Y'));
}

public function columns(): array
{
return [
Column::make('Index', 'id')->index(),

Column::make('ID', 'id'),

Column::add()
->title('Name')
->field('name')
->searchable()
->sortable(),

Column::add()
->title('Balance')
->field('balance')
->sortable(),

Column::add()
->title('Online')
->field('is_online'),

Column::add()
->title('Created At')
->field('created_at_formatted'),

Column::action('Action'),
];
}

public function actions($row): array
{
return [
Button::add('view')
->icon('default-eye', [
'class' => '!text-green-500',
])
->slot('View')
->class('text-slate-500 flex gap-2 hover:text-slate-700 hover:bg-slate-100 font-bold p-1 px-2 rounded')
->dispatch('clickToEdit', ['dishId' => $row?->id, 'dishName' => $row?->name]),
];
}

public function setTestThemeClass(string $themeClass): void
{
config(['livewire-powergrid.theme' => $themeClass]);
}
};

it('testings', function (string $component, object $params) {
livewire($component)
->call('setTestThemeClass', $params->theme)
->assertHasAction('view')
->assertActionContainsAttribute('view', 'class', 'flex gap-2 hover:text-slate-700')
->assertActionContainsAttribute('view', 'wire:click', 'clickToEdit', ['dishId' => 29, 'dishName' => 'Luan'])
->assertActionHasIcon('view', 'default-eye', '!text-green-500')
->assertOk();
})->with([
'tailwind' => [$component::class, (object) ['theme' => Tailwind::class]],
'bootstrap' => [$component::class, (object) ['theme' => Bootstrap5::class]],
]);