Test view rendered by blade or component class in Laravel
Bedram Tamang
Oct 31, 2018 ยท 2 min read

Test view in Laravel 8

Laravel (Laravel 8>) has provided a facility to test blade templates. For example: we have a blade template called home.blade.php and we are passing all the posts to the home.blade.php as:

...
    
class HomeController extends Controller
{
    public function index()
    {
        $posts = [
          "Post 1",
          "Post 2"
        ];

        return view("home.blade.php", compact("posts"));
    }
}

Now we can test if our blade templates built and rendered correctly. At first let's start by creating a new test class as:

php artisan make:test HomePageViewTest

and write the test case as:

<?php
    
namespace Tests\Feature;

use Tests\TestCase;

class HomePageViewTest extends TestCase
{
    /** @test */
    public function posts_is_rendered_in_home_page()
    {
        $posts = [
          "Post 1",
          "Post 2"
        ];

        $view = $this->view('home', $posts);

        $view->assertSee($post[0]);
    } 
}

Test Errors is rendered correctly.

Laravel has provided a method called withViewErrors to mock the errors in blade templates which could help you to test if errors are correctly rendered in laravel.

/** @test */
public function errors_are_rendered_correctly()
{
    $view = $this->withViewErrors([
    	'password' => ['Password must be at least 8 characters.']
	])->view('login');

    $view->assertSee("Password must be at least 8 characters.");
} 

Test Component

/** @test */
public function profile_component_is_rendered_correctly()
{
    $view = $this->component(Profile::class, ['name' => 'Taylor']);
		
	$view->assertSee('Taylor');
    $view->assertDontSee('Otwell');
} 

Conclusion

Testing view features provided by laravel is good improvements to test views. It allows to test blade templates either rendered by component class or view functions.


WRITTEN BY
Bedram Tamang
Laravel Developer

More From Web2tailwind


© 2019 - 2021 Web2tailwind.com