Summer Sale! All accounts are 50% off this week.

normykinz's avatar

Testing hashed password ... is it possible?

I'm not sure if this is possible.

I've made sure my phpunit.xml environment settings as the same as the dev encironment (including APP_KEY and BCRYPT_ROUNDS) but shis test fails.

it('encrypts the updated user password', function () {
    actingAs($this->user)
        ->livewire(Password::class)
        ->set('password', 'updated@password')
        ->set('password_confirmation', 'updated@password')
        ->call('submit');

    $this->assertTrue(Hash::check('updated@password', $this->user->password));
});

The Livewire component works as expected in the browser. It updates and hashes the passord as expected. But I don't know if it's even possible to test. Any pointers gratefully recieved,

0 likes
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@normykinz If you refresh the user data before asserting, does it works?

For example:

// Refresh the user model from the database
$this->user->refresh();

$this->assertTrue(Hash::check('updated@password', $this->user->password));
3 likes
LaryAI's avatar
Level 58

Yes, it is possible to test hashed passwords. However, in your test, you are not refreshing the user instance after the password update. This means that $this->user->password still contains the old password hash.

You need to refresh the user instance from the database after the password update to get the new password hash. Here is how you can do it:

it('encrypts the updated user password', function () {
    actingAs($this->user)
        ->livewire(Password::class)
        ->set('password', 'updated@password')
        ->set('password_confirmation', 'updated@password')
        ->call('submit');

    // Refresh the user instance to get the new password hash
    $this->user->refresh();

    $this->assertTrue(Hash::check('updated@password', $this->user->password));
});

The refresh() method will reload the current model instance with fresh data from the database. After calling this method, your user instance will have the updated password hash.

Please or to participate in this conversation.