Preview:
<?php

namespace Tests\Feature\Livewire;

use App\Livewire\CreatePost;
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class CreatePostTest extends TestCase
{
    #[Test]
    public function renders_successfully()
    {
        Livewire::test(CreatePost::class)
            ->assertStatus(200);
    }

    #[Test]
    public function can_create_new_post()
    {
        //delete the user if present
        Post::whereTitle('hello tashi')->delete();
        //to test if the title hello tashi is there or not
        //if returns a value test fails since no such data in the database
        $post = Post::whereTitle('hello tashi')->first();
        //should return null --> test successs
        $this->assertNull($post);

        //create a post with the title hello tenzin
        Livewire::test(CreatePost::class)
            ->set('title', 'hello tashi')
            ->set('content', 'hello tenzin content')
            ->call('save');

        //gettign the post just created with title hello tenzin
        $post = Post::whereTitle('hello tashi')->first();

        //to test it should return true since now there is a post with title hello tenzin
        $this->assertNotNull($post);
        //if the $post title not equals to hello tashi -- the test should fail
        $this->assertEquals('hello tashi', $post->title);
        //same same above
        $this->assertEquals('hello tenzin content', $post->content);
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter