In the next lessons, we will use built-in Livewire testing tools to test Livewire components.
The first one will be for the Questions, so first we need the Question factory.
php artisan make:factory QuestionFactory
database/factories/QuestionFactory.php:
class QuestionFactory extends Factory{ public function definition(): array { return [ 'question_text' => fake()->paragraph(), ]; }}
Because Questions needs an option we need to create a factory for the QuestionOption
Model.
php artisan make:factory QuestionOptionFactory
database/factories/QuestionOptionFactory.php:
class QuestionOptionFactory extends Factory{ public function definition(): array { return [ 'option' => fake()->text(), 'correct' => fake()->boolean(), 'question_id' => Question::factory(), ]; }}
This way we will be able to use the Factory Relationships feature.
Now let's create a feature test.
php artisan make:test Livewire/QuestionsTest
tests/Feature/Livewire/QuestionsTest.php:
use App\Models\User;use Livewire\Livewire;use App\Models\Question;use App\Models\QuestionOption;use App\Livewire\Questions\QuestionForm;use Illuminate\Foundation\Testing\RefreshDatabase; class QuestionsTest extends TestCase{ use RefreshDatabase; public function testAdminCanCreateQuestion() { $this->actingAs(User::factory()->admin()->create()); Livewire::test(QuestionForm::class) ->set('question_text', 'very secret question') ->set('questionOptions.0.option', 'first answer') ->call('save') ->assertHasNoErrors(['question_text', 'code_snippet', 'answer_explanation', 'more_info_link', 'topic_id', 'questionOptions', 'questionOptions.*.option']) ->assertRedirect(route('questions')); $this->assertDatabaseHas('questions', [ 'question_text' => 'very secret question', ]); } public function testQuestionTextIsRequired() { $this->actingAs(User::factory()->admin()->create()); Livewire::test(QuestionForm::class) ->set('question_text', '') ->call('save') ->assertHasErrors(['question_text' => 'required']); } public function testAdminCanEditQuestion() { $this->actingAs(User::factory()->admin()->create()); $question = Question::factory() ->has(QuestionOption::factory()) ->create(); Livewire::test(QuestionForm::class, [$question]) ->set('question_text', 'very secret question') ->call('save') ->assertHasNoErrors(['question_text', 'code_snippet', 'answer_explanation', 'more_info_link', 'topic_id', 'questionOptions', 'questionOptions.*.option']) ->assertRedirect(route('questions')); $this->assertDatabaseHas('questions', [ 'question_text' => 'very secret question', ]); }}
In this feature test, we test the QuestionForm
Livewire component if the form has no errors and creates and updates the question. In one of the tests we also test if the validation rule works as expected.