mstdmstd
mstdmstd

Reputation: 3071

Why I got error making livewire test with bool field casted as enum?

In laravel 11 / livewire app I make test on a for with empty fields ?

#[Test]
public function on_new_article_got_validation_errors()
{
    Livewire::test(ArticleEditor::class)
        ->set('articleId', null)  // Form in Add mode
        ->set('form.category_id', null)
        ->set('form.title', '')
        ->set('form.rating', null)

        ->set('form.text_shortly', '')
        ->set('form.text', '')
        ->set('form.published', null)
        ->call('store')
        ->assertHasErrors(['form.category_id', 'form.title', 'form.rating', 'form.text_shortly', 'form.text', 'form.published' ]);
}

and I got error :

Tests\Feature\Livewire\Admin\AdminArticlesCRUDTests > on new article got validation errors
  Component missing error: form.published
Failed asserting that false is true.

In app/Livewire/Forms/ArticleForm.php for published(defined as bool in migration) enum is used with definition in app/Enums/ArticlePublishedEnum.php :

<?php

namespace App\Enums;

enum ArticlePublishedEnum: int
{
    // These values are the same as enum values in db
    case PUBLISHED = 1;
    case NOT_PUBLISHED = 0;
}

and in the app/Livewire/Forms/ArticleForm.php form :

<?php

namespace App\Livewire\Forms;

use App\Enums\ArticlePublishedEnum;
    ...
    public ?ArticlePublishedEnum $published = null;


    public function store(): Article
    {
        $article = Article::create([
            ...
            'published' => $this->published ?? ArticlePublishedEnum::NOT_PUBLISHED,
            ...
        ]);

        return $article;
    }

and in the model :

class Article extends Model implements HasMedia
{
    protected $table = 'articles';
    protected $primaryKey = 'id';
    public $timestamps = false;
    ...
    protected $casts = [ 'created_at' => 'datetime', 'updated_at' => 'datetime', 'published' => ArticlePublishedEnum::class];

in validation rules :

    'form.published' => [
        'nullable',
    ],

if in my tests I comments ->set('form.published', null) and 'form.published' the the test passes ok.

Any ideas what is wrong and how test bool published field ?

Upvotes: 0

Views: 7

Answers (0)

Related Questions