3
votes

I use sendGrid email in my nodejs app

https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail

And basically, when user signs up, I will send a welcome email

But when I write test for user sign up, I want to mock sendgrid send function. How can I do it with jest. Or any suggestion on how can I test the signup api

2

2 Answers

2
votes

For the javascript/node version of sendgrid we added the following:

mail_settings: {
      sandbox_mode: {
          enable: process.env.NODE_ENV === 'test',
      },
  }

so it looked like this in context:

const msg =  {
      to: email,
      from: EMAIL_FROM,
      subject,
      replyTo: REPLY_TO,
      dynamicTemplateData,
      templateId,
      mail_settings: {
          sandbox_mode: {
              enable: process.env.NODE_ENV === 'test',
          },
      }
  };
  sgMail.send(msg)

This solution came from coinhndp along with additional info on syntax from github. It works because when we run npm test the scripts set our environment to 'test', which then sets sandbox_mode { enable: true }.

To get it working with jest we have a jestSetup.js file:

jest.setTimeout(15000);

jest.mock('@sendgrid/mail');
const sgMail = require('@sendgrid/mail');
const defaultMailOptions = { response: 'Okay' };

beforeAll(() => {
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);
});

beforeEach(() => {
  global.mockMailer = (options=defaultMailOptions) => {
    return sgMail.sendMultiple.mockImplementation(() => Promise.resolve(options));
  };
});

afterEach(() => {
  jest.clearAllMocks();
});

Which allows us to add beforeEach(() => mockMailer()); to our tests. It's worth noting that we only use sendMultiple() for sending emails with sendgrid, you may be using a different function in your application.