F
Filament3mo ago
Kovah

How to test Filament widgets?

I am a bit lost right now. I try to test a Filament (v3) widget via Pest/PhpUnit, but can't just get it to work. The stats widget itself is nothing special, the only code is in the getStats() method which returns a few Stat components. The getStats() method is protected by default, so I would need a reflection class to access that data, which feels wrong. My second idea was to just render the HTML, but that leads to an error.
test('Costs for upcoming domain renewals are calculated correctly', function () {
Domain::factory()->create([
'next_renewal' => now()->addMonth(),
'price' => 10,
'status' => DomainStatus::Active->value,
]);

$html = (new DomainCostsWidget)->render();
$this->assertStringContainsString('10', $html);
});
test('Costs for upcoming domain renewals are calculated correctly', function () {
Domain::factory()->create([
'next_renewal' => now()->addMonth(),
'price' => 10,
'status' => DomainStatus::Active->value,
]);

$html = (new DomainCostsWidget)->render();
$this->assertStringContainsString('10', $html);
});
Illuminate\View\ViewException: Using $this when not in object context
Illuminate\View\ViewException: Using $this when not in object context
Unfortunately, there is no official documentation on that, and after looking through the base widget classes, it seems that there is no way to properly get the data without initializing it first, which seems to happen only internally. Has anyone solved this? Can't imagine that people just create widgets without testing what they return. Also, moving the business logic into a separate class feels equally wrong.
Solution:
I think they are livewire components. Did you try testing them via the Livewire helper?
Jump to solution
2 Replies
Solution
Dennis Koch
Dennis Koch3mo ago
I think they are livewire components. Did you try testing them via the Livewire helper?
Kovah
KovahOP3mo ago
Aww man, I feel so stupid. Of course that worked. Thanks for the hint!

Did you find this page helpful?