To write tests for custom Laravel Nova Actions, you can follow these steps:
-
Create a new test file for your Nova Action. For example, if your Action is called "TopUpParticipant", you can create a file named "TopUpParticipantTest.php" in the "tests/Feature" directory.
-
In the test file, you can use the
Novafacade to perform the action on the given models. You can use theactingAsmethod to authenticate a user and thepostmethod to send a POST request to the Nova action endpoint. -
Write test methods to cover different scenarios. For example, you can write a test method to check if the action returns the correct message when the top-up is successful, and another test method to check if the action returns the correct error message when trying to top-up multiple participants at once.
Here's an example of how the test file could look like:
<?php
namespace Tests\Feature;
use App\Nova\Participant;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Fields\ActionFields;
use Tests\TestCase;
class TopUpParticipantTest extends TestCase
{
public function testTopUpParticipant()
{
$user = // create or get a user to authenticate as
$participant = // create or get a participant to top-up
$response = $this->actingAs($user)
->postJson('/nova-api/participants/top-up', [
'resources' => [$participant->id],
'fields' => [
'amount' => 100,
],
]);
$response->assertStatus(200)
->assertJson([
'message' => 'You did a top-up of € 100 for ' . $participant->name,
]);
// Assert that the participant's wallet has been updated correctly
$this->assertEquals(100, $participant->fresh()->wallet);
}
public function testTopUpMultipleParticipants()
{
$user = // create or get a user to authenticate as
$participants = // create or get multiple participants to top-up
$response = $this->actingAs($user)
->postJson('/nova-api/participants/top-up', [
'resources' => $participants->pluck('id')->toArray(),
'fields' => [
'amount' => 100,
],
]);
$response->assertStatus(200)
->assertJson([
'danger' => 'You can only top-up one participant at a time.',
]);
// Assert that the participants' wallets have not been updated
$participants->each(function ($participant) {
$this->assertEquals(0, $participant->fresh()->wallet);
});
}
}
Make sure to replace the placeholders ($user, $participant, $participants) with the appropriate code to create or get the required user and participant models.
Note: The example assumes that you have set up Laravel Nova and have the necessary routes and authentication in place.