我在我的nodejs应用程序中使用sendGrid电子邮件服务。
详见:https://github.com/sendgrid/sendgrid-nodejs/tree/master/packages/mail
基本上,当用户注册时,我会发送欢迎电子邮件。但是,当我为用户注册编写测试时,我想模拟sendgrid发送功能。我应该如何使用jest来实现它?或者,请给予测试注册api的任何建议。
针对JavaScript/Node版本的SendGrid,我们添加了以下内容:
mail_settings: {
sandbox_mode: {
enable: process.env.NODE_ENV === 'test',
},
}
所以,在上下文中看起来像这样:
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)
这个解决方案来自coinhndp,同时还有来自github的语法附加信息。它能够成功运行是因为当我们运行npm test
时,脚本会将我们的环境设置为'test'
,然后设置sandbox_mode { enable: true }
。
为了使其与jest协同工作,我们需要一个jestSetup.js
文件:
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();
});
这使我们能够在测试中添加 beforeEach(() => mockMailer());
。值得注意的是,我们只在使用sendgrid发送邮件时使用sendMultiple()函数,您可能在应用程序中使用了不同的函数。
jest.mock()
编写了一个解决方案,我将在答案中更新她所写的内容。 - Greyphilosophy