Laravel Unit Test (The response is not a view)

I am doing unit testing to my web application. My experience with Laravel and PHP Unit Testing too young. Now, I am just fiddling around with the Laravel Unit test. Now, I am testing if a view returned to the route contains specific text. Very simple. This is what I have done.

I created a view called, unit_test.blade.php with the following content

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    This is unit test
</body>
</html>

This is the route to display that view

Route::get('unit/test', function(){
   return view('unit_test');
});

This is my test class and function

class ApiV2EventController extends TestCase
{


    public function testUnitTest()
    {
        $response = $this->get('unit/test');

        $response->assertViewHas('unit');
    }
}

My test function is simple. It is just checking if the view contains the text, "unit". But when I run the test in the command line, it is giving

There was 1 failure:

1) Tests\Feature\ApiV2EventController::testUnitTest
The response is not a view.

I am returning the view in the route. What is wrong with my code? How can I test it?

1 answer

  • answered 2018-07-20 17:46 Armando Garza

    As mentioned in the comments, you can use $response->content() in the test case to check the actual rendered HTML.

    And an extra: you can use $response->assertSeeText($string) to check that any string exists in the HTML. That method is pretty much what you did ($this->assertContains('unit', $response->content())) with an extra call to strip_tags().

    And as another extra, $response->assertViewHas() is used when you pass data to your view, e.g.

    Route::get('unit/test', function() {
        return view('unit_test', [
            'some_var' => 'some value',
        ]);
    });
    

    And in the test case:

    $response = $this->get('unit/test');
    $response->assertViewHas('some_var');