使用 Mocha 和 Sinon 测试 Mailgun .send() 方法

Adi*_*ran 3 unit-testing mocha.js node.js sinon mailgun

我正在尝试为通过 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);
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

测试文件:

  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();    
    });
Run Code Online (Sandbox Code Playgroud)

运行结果npm test

TypeError: [Function] is not a spy or a call to a spy!
Run Code Online (Sandbox Code Playgroud)
  1. 如何测试.send方法是否被调用mailgun.messages().send(...)

  2. 我直接使用mailgun API。我怎样才能剔除 mailgun 本身?

okt*_*dia 5

你必须存根,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();
Run Code Online (Sandbox Code Playgroud)

您可以使用sandbox.spy()来检查您想要的内容,行为与此处的 Doc相同sinon.spy()