Skip to content
Advertisement

How to assert paginations in Laravel?

I have a category model with the following method:

public static function index()
{
    return self::has('posts')->paginate(1);
}

My category controller:

public function index()
{
    $categories = Category::index();
    return view('categories.index', compact('categories'));
}

This is what I’ve tried, I am using RefreshDatabase trait.

public function test_index_view_is_working()
{
    factory(Post::class, 5)->create();
    $response = $this->get(route('categories.index'));
    $response->assertViewHas('categories', Category::index());
}

This test fails for some reason:

Failed asserting that two objects are equal.

at tests/Feature/CategoryTest.php:38
    37|         $response->assertViewIs('categories.index');
  > 38|         $response->assertViewHas('categories', Category::index());

--- Expected
+++ Actual
@@ @@
                 'dispatchesEvents' => Array ()
                 'observables' => Array ()
                 'relations' => Array (
+                    'posts' => IlluminateDatabaseEloquentCollection Object (...)
                 )
                 'touches' => Array ()
                 'timestamps' => true

Advertisement

Answer

The reason you get this error is because somehow the posts are eager loaded from the view/controller but not from the tests.

I’m guessing return self::has('posts')->with('posts')->paginate(1); could fix it.

Alternatively, you can test if you have the pagination at the bottom the page. Since {{ $categories->links() }} will add something like Previous and Next you can still look for it.

$response = $this->get(route('categories.index'));
$response->assertSee('Next');

Also, you can ensure that you paginate the categories but it won’t ensure you have added the links at the bottom of the page.

use IlluminateContractsPaginationPaginator;
...

$response = $this->get(route('categories.index'));
$this->assertInstanceOf(Paginator::class, $response->viewData('categories'));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement