zenstruck / messenger-test

Assertions and helpers for testing your symfony/messenger queues.
MIT License
218 stars 15 forks source link

Can't access to html body of the email #58

Open clemcoder opened 1 year ago

clemcoder commented 1 year ago

Hello,

I try to test the html content of an email (I want to check a particular link inside). Here is the code :

        $asyncMessengerTransport = $this->messenger('async');
        $asyncMessengerQueue = $asyncMessengerTransport->queue();

        $asyncMessengerQueue->assertCount(1);

        $firstMessage = $asyncMessengerQueue->first()->getMessage();
        $email = $firstMessage->getMessage();
        $htmlBody = $email->getHtmlBody();

Unfortunately getHtmlBody always returns null. Is there a probleme in this code ? Is it possible to test the content of the email ?

Thanks.

kbond commented 1 year ago

Hi @clemcoder!

I'm wondering if it is there but during serialization, it is lost from getHtmlBody(). What does the following output?

dd($email->getBody()->toString());

Do you see the html?

Is it possible to test the content of the email ?

I recommend checking out zenstruck/mailer-test. This provides email-related assertions and supports queued emails.

clemcoder commented 1 year ago

It outputs "Symfony\Component\Mime\Exception\LogicException: A message must have a text or an HTML part or attachments.". I don't see the html, just the twig template name in the htmlTemplate attribute of TemplatedEmail object . However I do see the content of the sended message in MailDev.

I didn't know about zenstruck/mailer-test, I'll take a look.

Thanks for your help.

kbond commented 1 year ago

Oh! You'll need to process the queue before you can see the html.

I think the following will work:

$asyncMessengerTransport = $this->messenger('async');

$asyncMessengerTransport->queue()->assertCount(1);
$asyncMessengerTransport->process();

$firstMessage = $asyncMessengerTransport->acknowledged()->first()->getMessage();
$email = $firstMessage->getMessage();
$htmlBody = $email->getHtmlBody();
clemcoder commented 1 year ago

Nop, unfortunately already tried. I just test your code and htmlBody always null :(.

kbond commented 1 year ago

Hmm ok, I guess processing the email doesn't manipulate the message. At the end of the day I believe this makes sense and is expected.

I guess you can't use messenger-test to test the processing of emails. zenstruck/mailer-test should work for you.