cypress-mailhog
cypress-mailhog copied to clipboard
Parse e-mails using mailparser to get decoded plain-text
I had problems with a test where the assertion was unable to find a certain string in the e-mail body since it was encoded. More specifically, special chars were encoded and line breaks where added mid-word (I still don't know the reason for that). The plain-text was encoded using the quoted-printable pattern. I found a library for decoding but first I would need to extract the encoded plain-text from the e-mail. At that point I decided to integrate mailparser to properly access the e-mail contents.
I believe cypress-mailhog
could benefit from this solution, but I don't have the resources to make a PR myself, right now. So here is how I integrated mailparser, maybe someone else has the time to do this properly.
First, add a new command:
// cypress/support/index.d.ts
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable {
mhParseMail(): Chainable<string>
}
}
// cypress/support/commands.ts
/// <reference path="../../node_modules/cypress-mailhog/types/mailhog.d.ts" />
Cypress.Commands.add('mhParseMail', { prevSubject: true }, (mail: any) => {
return cy.task('parse-mail', { mail: (mail as mailhog.Item).Raw.Data })
})
As you can see, this command calls a task. Sadly, mailparser is not browser-compatible:
// cypress/plugins/index.js
const simpleParser = require('mailparser').simpleParser
module.exports = async (on, config) => {
on('task', {
'parse-mail': ({ mail }) => simpleParser(mail),
})
}
Obviously, we also need to install mailparser
: npm i -D mailparser
.
Then in your test, you can use it like this:
// ...
cy.mhGetMailsByRecipient('[email protected]')
.mhFirst()
.mhParseMail()
.its('text')
.should('contain', 'foo')
Now that we have mailparser integrated, you can also use it to access lots of other properties. See the mailparser
docs for details: https://nodemailer.com/extras/mailparser/#mail-object