用Mocha和SinontestingMailgun .send()方法

我正在尝试编写一个快速中间件函数的unit testing,通过ping Mailgun API来发送电子邮件。

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); }); } }; 

testing文件:

  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! 
  1. 如何在mailgun.messages().send(...)调用.send方法?

  2. 我直接使用mailgun API。 我怎样才能将邮件本身存根?

您必须存根mailgun-js您必须存根这个包裹并且在您能检查您想要的回归之后

因为你正在使用callback,不要忘记返回它

 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()一样

如何在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'}传递给它所创build的第一个callback函数。

我想它也回答你的另一个问题。