Mocking email function in nodejs

前端 未结 4 1870
我寻月下人不归
我寻月下人不归 2021-02-05 09:29

I\'ve got a mailer function I\'ve built and trying to shore up the coverage. Trying to test parts of it have proven tricky, specifically this mailer.smtpTransport.sendMail

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 10:21

    You can directly mock the sendMail function but it's not obvious how to access it from the tests. A Mailer instance is returned when you create a transport so you need to directly import that class in to your test.

    const Mailer = require('nodemailer/lib/mailer')
    

    Then you can mock or stub the sendMail method on the prototype in the usual way. Using Jasmine, you can do it like this:

    beforeEach(function () {
      spyOn(Mailer.prototype, 'sendMail').and.callFake(function (mailOptions, cb) {
        cb(null, true)
      })
    })
    

    The callFake ensures that the sendMail's callback is still executed encase you need to test what happens next. You can easily simulate an error by passing a first argument to cb: cb(new Error('Email failed'))

    Now that the mock is set up, you can check everything is working as intended:

    expect(Mailer.prototype.sendMail).toHaveBeenCalled()
    

提交回复
热议问题