Jamie Woods
Jamie Woods

Reputation: 579

Testing Laravel Nova

Currently I'm trying to write feature tests for laravel nova that assert that the page is loaded correctly and data can be seen.

However when I write the tests I can't find a way to assert that the correct text is shown due to way laravel nova's data is produce. Ontop of that I can't seem to test if a page loads correctly with laravel nova's 404 page coming back as a 200 response when a resource page that doesn't exist loads.

Has anyone found a good way to feature test nova?

Upvotes: 15

Views: 6610

Answers (3)

osama Abdullah
osama Abdullah

Reputation: 321

I had the same issue, I found out that the gate in App\Providers\NovaServiceProvider.php is not letting users pass, just return true when testing only and everything must work as expected

    protected function gate()
{
    Gate::define('viewNova', function ($user) {

        return true;
    });
}

Upvotes: -4

thomas_inckx
thomas_inckx

Reputation: 470

TL;DR: check out this repo: https://github.com/bradenkeith/testing-nova. It has helped me find my way on how to test Laravel Nova.

Laravel Nova is basically a CRUD framework. So I'm assuming that, when you say

"that the page is loaded correctly and data can be seen"

You actually mean: my resources are loaded correctly. Or, I can create/update/delete a resource. This is because Nova is loading its resource info asynchronous via api calls. So that's why, a good method to test your logic is to test the /nova-api/ routes.

For example:

<?php

namespace Tests\Feature\Nova;

use App\Note;
use Tests\TestCase;

class NoteTest extends TestCase
{
  public function setUp(): void
  {
    parent::setUp();
  }

  /** @test */
  public function it_gets_a_note()
  {
    // given 
    $note = factory(Note::class)->create();

    $response = $this->get('/nova-api/notes/' . $note->id)
      ->assertStatus(200)
      ->assertJson([
        'resource'  =>  [
          'id'    =>  [
            'value' =>  $note->id
          ]
        ]
    ]);
  }
}

By calling the route https://my-app.test/resources/notes/1, we can assert that we're getting a 200 response (successful) and that we're actually returning our newly created Note. This is a pretty trustworthy test to be sure a resource detail page is working fine.

If, however, you are talking about Browser Testing, you might want to take a look at Laravel Dusk:

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API.

Once installed, you can start real browser testing:

$user = factory(User::class)->create();
$user->assignRole('admin');

$this->browse(function (Browser $browser) use ($user) {
  $browser
    ->loginAs($user)
    ->visit('/')
    ->assertSee('Dashboard');
});

Upvotes: 21

Pnj Patel
Pnj Patel

Reputation: 1

Add on app/config file in your project directory:

App\Providers\NovaServiceProvider::class,

Upvotes: -11

Related Questions