title: Testing Mailgun .send() method with Mocha and Sinon
body: <p>I am trying to write unit tests for an express middleware function that sends an email by pinging the Mailgun API.</p>
  
  <pre><code>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);
      });
    }
  };
  </code></pre>
  
  <p>The test file:</p>
  
  <pre><code>  describe('\'sendEmail\' method', () =&gt; {
      let mailgun;
      beforeEach(() =&gt; {
        mailgun = require('mailgun-js')({ apiKey: MAIL_GUN_API_KEY, domain: MAIL_GUN_DOMAIN });
      });
  
      it.only('should send the data to the MailGun API', (done) =&gt; {    
        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();    
      });
  </code></pre>
  
  <p>Result upon running <code>npm test</code>:</p>
  
  <pre><code>TypeError: [Function] is not a spy or a call to a spy!
  </code></pre>
  
  <blockquote>
    <ol>
    <li><p>How can I test if the <code>.send</code> method is being called in <code>mailgun.messages().send(...)</code>?</p></li>
    <li><p>I am directly using the mailgun API. How can I stub out mailgun itself?</p></li>
    </ol>
  </blockquote>