在node.js中使用Jest和Mock测试Sendgrid实现



我在我的nodejs应用程序中使用sendGrid电子邮件,我想用jest测试它。

这是我的应用代码:

邮件.js

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const simplemail = () => {
const msg = {
to: 'receiver@mail.com',
from: 'sender@test.com',
subject: 'TEST Sendgrid with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
mail_settings: {
sandbox_mode: {
enable: true,
},
},
};
(async () => {
try {
console.log(await sgMail.send(msg));
} catch (err) {
console.error(err.toString());
}
})();
};
export default simplemail;

这是我开玩笑地测试它所做的:

邮件测试.js

import simplemail from './mail';
const sgMail = require('@sendgrid/mail');
jest.mock('@sendgrid/mail', () => {
return {
setApiKey: jest.fn(),
send: jest.fn(),
};
});
describe('#sendingmailMockedway', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('Should send mail with specefic value', async () => {
// sgMail.send.mockResolvedValueOnce([{}, {}]);
await expect(sgMail.send).toBeCalledWith({
to: 'receiver@mail.com',
from: 'sender@test.com',
subject: 'TEST Sendgrid with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
});
});
});

我需要在这个文件上修复我的代码覆盖率,以便进行尽可能多的测试并测试邮件是否已发送并捕获是否有错误或现在,这就是我在邮件中添加的原因.js

mail_settings: {
sandbox_mode: {
enable: true,
},
},

我想用开玩笑和模拟发送网格来测试它,但是如何呢?

由于您在simplemail函数中使用 IIFE 和async/await,因此在单元测试用例中断言 IIFE 之前,请使用setImmediate函数确保 IIFE 已执行。

下面是单元测试解决方案:

index.js

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const simplemail = () => {
const msg = {
to: "receiver@mail.com",
from: "sender@test.com",
subject: "TEST Sendgrid with SendGrid is Fun",
text: "and easy to do anywhere, even with Node.js",
html: "<strong>and easy to do anywhere, even with Node.js</strong>",
mail_settings: {
sandbox_mode: {
enable: true
}
}
};
(async () => {
try {
console.log(await sgMail.send(msg));
} catch (err) {
console.error(err.toString());
}
})();
};
export default simplemail;

index.spec.js

import simplemail from "./";
const sgMail = require("@sendgrid/mail");
jest.mock("@sendgrid/mail", () => {
return {
setApiKey: jest.fn(),
send: jest.fn()
};
});
describe("#sendingmailMockedway", () => {
afterEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
});
it("Should send mail with specefic value", done => {
const logSpy = jest.spyOn(console, "log");
const mResponse = "send mail success";
sgMail.send.mockResolvedValueOnce(mResponse);
simplemail();
setImmediate(() => {
expect(sgMail.send).toBeCalledWith({
to: "receiver@mail.com",
from: "sender@test.com",
subject: "TEST Sendgrid with SendGrid is Fun",
text: "and easy to do anywhere, even with Node.js",
html: "<strong>and easy to do anywhere, even with Node.js</strong>",
mail_settings: {
sandbox_mode: {
enable: true
}
}
});
expect(logSpy).toBeCalledWith(mResponse);
done();
});
});
it("should print error when send email failed", done => {
const errorLogSpy = jest.spyOn(console, "error");
const mError = new Error("network error");
sgMail.send.mockRejectedValueOnce(mError);
simplemail();
setImmediate(() => {
expect(sgMail.send).toBeCalledWith({
to: "receiver@mail.com",
from: "sender@test.com",
subject: "TEST Sendgrid with SendGrid is Fun",
text: "and easy to do anywhere, even with Node.js",
html: "<strong>and easy to do anywhere, even with Node.js</strong>",
mail_settings: {
sandbox_mode: {
enable: true
}
}
});
expect(errorLogSpy).toBeCalledWith(mError.toString());
done();
});
});
});

100% 覆盖率的单元测试结果:

PASS  src/stackoverflow/59108624/index.spec.js (6.954s)
#sendingmailMockedway
✓ Should send mail with specefic value (9ms)
✓ should print error when send email failed (17ms)
console.log node_modules/jest-mock/build/index.js:860
send mail success
console.error node_modules/jest-mock/build/index.js:860
Error: network error
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.336s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59108624

最新更新