Node.js 使用Mocha和Sinon测试Mailgun.send()方法
我正在尝试为express中间件函数编写单元测试,该函数通过ping mailgunAPI发送电子邮件Node.js 使用Mocha和Sinon测试Mailgun.send()方法,node.js,unit-testing,mocha.js,sinon,mailgun,Node.js,Unit Testing,Mocha.js,Sinon,Mailgun,我正在尝试为express中间件函数编写单元测试,该函数通过ping mailgunAPI发送电子邮件 module.exports = { sendEmail: function (req, res) { let reqBody = req.body; let to = reqBody.to; let from = reqBody.from; let subject = reqBody.subject; let emailBody = reqBody
module.exports = {
sendEmail: function (req, res) {
let reqBody = req.body;
let to = reqBody.to;
let from = reqBody.from;
let subject = reqBody.subject;
let emailBody = reqBody.body;
let data = {
from: from,
to: to,
subject: subject,
text: emailBody
};
mailgun.messages().send(data, function (error, body) {
if (error) {
res.status(400).json(error);
return;
}
res.status(200).json(body);
});
}
};
测试文件:
describe('\'sendEmail\' method', () => {
let mailgun;
beforeEach(() => {
mailgun = require('mailgun-js')({ apiKey: MAIL_GUN_API_KEY, domain: MAIL_GUN_DOMAIN });
});
it.only('should send the data to the MailGun API', (done) => {
sinon.spy(mailgun, 'messages');
sinon.spy(mailgun.messages(), 'send');
emailMiddleware.sendEmail(request, response);
// using sinon-chai here
mailgun.messages().send.should.have.been.called();
done();
});
运行npm测试时的结果
:
TypeError: [Function] is not a spy or a call to a spy!
mailgun.messages().send(…)
中是否调用了.send
方法send
,而不仅仅是监视它并使它像真正的方法一样工作
这就是我在想存根mailgun js模块时所做的
// Mock sandbox
sandbox = sinon.sandbox.create()
mailgunSendSpy = sandbox.stub().yields(null, { bo: 'dy' })
sandbox.stub(Mailgun({ apiKey: 'foo', domain: 'bar' }).Mailgun.prototype, 'messages').returns({
send: mailgunSendSpy
})
yields
方法将参数null
和{bo:'dy'}
传递给它找到的第一个回调
我想它也回答了你的另一个问题。你必须存根
mailgun js
你必须存根这个包,然后你可以检查你想要的退货
因为您正在使用回调,所以不要忘记返回它
const sandbox = sinon.sandbox.create();
sandbox.stub(mailgun({ apiKey: 'foo', domain: 'bar' }).Mailgun.prototype, 'messages')
.returns({
send: (data, cb) => cb(),
});
// Your stuff...
sandbox.restore();
您可以使用sandbox.spy()
检查所需内容,其行为与sinon.spy()相同
const stubs = {};
//Make a stub for the send method.
stubs.mailgunSendStub = sinon.stub(
{ send: () => new Promise((resolve) => resolve(null)) },
'send'
);
stubs.mailgunMessagesStub = sinon
.stub(mailgun({ apiKey: 'k', domain: 'd' }).Mailgun.prototype, 'messages')
.returns({
send: stubs.mailgunSendStub, //call it here.
});
//Now you can test the call counts and also the arguments passed to the send() method.
expect(stubs.mailgunSendStub.callCount).toBe(1);
expect(stubs.mailgunSendStub.args[0][0]).toStrictEqual(someData);