Jest mock sendgrid send email

Viewed 3976
2 Answers

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.

You can use sendgrid's sandbox mode to avoid emails actually being sent

Related