Search code examples
node.jsexpressjestjsnodemailer

Node.JS: Refreshing the nodemailer-mock after each test in Jest


I am building a Node JS application using Express.js framework. My application is sending email using the nodemailer package, https://nodemailer.com/about/. I am writing test using supertest and Jest. I am using nodemailer-mock package, https://www.npmjs.com/package/nodemailer-mock to mock my application.

I can mock the logic for sending email for Jest as mentioned in the nodemailer-mock documentation. The only issue is that it is not resetting the data/ count after each test. For example, I have two tests and both are sending emails and when I do the following assertion, it is failing.

const sentEmails = mock.getSentMail();
    // there should be one
    expect(sentEmails.length).toBe(1);

It is failing because an email was sent in the previous test. How can I reset it?


Solution

  • Assuming your mock variable is set (or even imported) at the module level, this should cover it:

    afterEach(() => {
        mock.reset();
    });
    

    Keep in mind that this method also seems to reset anything else you have configured on the mock (success response, fail response, etc.), so you may need to perform that setup each time too. That would be a good fit for a beforeEach block.