cinameng's avatar

Unable to match User in Dusk test for Login

I have a Dusk test that creates a user and then attempts to login using the record it has just created however the page under test responds as if it cannot find a match for the users record.

 public function testLogin(): void
{
    $user = User::factory()->create(
        [
            'email' => '[email protected]',
        ],
    );

    $this->browse(function (Browser $browser)  use ($user) {
        $browser->visit(new Login)
            ->type('input[name=login_key]', $user->email)
            ->press('input[type=submit]')
            ->assertSee('You have been sent an email');
    });
}

Expected Result: ->assertSee('You have been sent an email');

Actual Result: ->assertSee('Invalid Login');

dd($user->email) 

the correct email address is returned.

I seem to remember something liek this happening before where I had to somehow persist the data but I cannot remember what it was.

0 likes
4 replies
LaryAI's avatar
Level 58

It seems like the issue is that the user record is not persisting in the database when the test is running. To resolve this, you can use the create method from the DatabaseTransactions trait provided by Laravel Dusk.

Here's an updated version of the test method that includes the DatabaseTransactions trait:

use Illuminate\Foundation\Testing\DatabaseTransactions;

public function testLogin(): void
{
    $this->browse(function (Browser $browser) {
        $user = User::factory()->create([
            'email' => '[email protected]',
        ]);

        $browser->visit(new Login)
            ->type('input[name=login_key]', $user->email)
            ->press('input[type=submit]')
            ->assertSee('You have been sent an email');
    });
}

By using the DatabaseTransactions trait, the test will wrap the entire test method in a database transaction. This means that any changes made to the database during the test will be rolled back after the test completes, ensuring a clean state for each test.

Make sure to include the use Illuminate\Foundation\Testing\DatabaseTransactions; statement at the top of your test file.

Let me know if this helps!

cinameng's avatar

if I add

$this->assertDatabaseHas('users', [
        'email' => '[email protected]',
    ]);

the assertion passes which suggests that the data has been stored correctly.

tisuchi's avatar

@cinameng In the login test, why do you expect to see You have been sent an email message?

cinameng's avatar

@tisuchi sorry I should have said, it's a passwordless authentication.

I think my issue is to do with my database configuration as when I dd the user variable it returns the email but when I look in the database that the tests are using there is nothing there.

Please or to participate in this conversation.