我正在尝试为一个使用Mailgun API发送电子邮件的express中间件函数编写单元测试。
测试文件:
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 test
运行后的结果如下:
TypeError: [Function] is not a spy or a call to a spy!
如何测试在
mailgun.messages().send(...)
中是否调用了.send
方法?我直接使用mailgun API。如何桩mock mailgun本身?