Skip to content

Instantly share code, notes, and snippets.

@jrushlow
Created March 26, 2024 15:57
Show Gist options
  • Save jrushlow/193798c452a6e135c883273277e05621 to your computer and use it in GitHub Desktop.
Save jrushlow/193798c452a6e135c883273277e05621 to your computer and use it in GitHub Desktop.
Quick and dirty reset password test
<?php
namespace App\Tests\Functional;
use App\Entity\User;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class ResetPasswordControllerTest extends WebTestCase
{
public function testMaker(): void
{
$client = static::createClient();
/** @var EntityManager $em */
$em = static::getContainer()->get('doctrine')->getManager();
$client->request('GET', '/reset-password');
self::assertResponseIsSuccessful();
self::assertPageTitleContains('Reset your password');
$repository = $em->getRepository(User::class);
foreach ($repository->findAll() as $envUser) {
$em->remove($envUser);
}
$em->flush();
$user = (new User())
->setEmail('me@example.com')
->setPassword('password')
;
$em->persist($user);
$em->flush();
$client->submitForm('Send password reset email', [
'reset_password_request_form[email]' => 'me@example.com',
]);
self::assertQueuedEmailCount(1);
// self::assertEmailCount(1);
$messages = $this->getMailerMessages();
self::assertCount(1, $messages);
self::assertEmailAddressContains($messages[0], 'to', 'me@example.com');
self::assertEmailTextBodyContains($messages[0], 'This link will expire in 1 hour.');
self::assertResponseRedirects('/reset-password/check-email');
$crawler = $client->followRedirect();
self::assertPageTitleContains('Password Reset Email Sent');
self::assertStringContainsString('This link will expire in 1 hour', $crawler->html());
$email = $messages[0]->toString();
preg_match('#(/reset-password/reset/[a-zA-Z0-9]+)#', $email, $resetLink);
$client->request('GET', $resetLink[1]);
self::assertResponseRedirects('/reset-password/reset');
$client->followRedirect();
$client->submitForm('Reset password', [
'change_password_form[plainPassword][first]' => 'newStrongPassword',
'change_password_form[plainPassword][second]' => 'newStrongPassword',
]);
self::assertResponseRedirects('/');
$user = $em->getRepository(User::class)->findOneBy(['email' => 'me@example.com']);
/** @var UserPasswordHasherInterface $passwordHasher */
$passwordHasher = static::getContainer()->get(UserPasswordHasherInterface::class);
self::assertTrue($passwordHasher->isPasswordValid($user, 'newStrongPassword'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment