Mocking email function in nodejs

前端 未结 4 1872
我寻月下人不归
我寻月下人不归 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:01

    This example works fine for me

    ======== myfile.js ========

    // SOME CODE HERE
    
    transporter.sendMail(mailOptions, (err, info) => {
      // PROCESS RESULT HERE
    });
    

    ======== myfile.spec.js (unit test file) ========

    const sinon = require('sinon');
    const nodemailer = require('nodemailer');
    const sandbox = sinon.sandbox.create();
    
    describe('XXX', () => {
      afterEach(function() {
        sandbox.restore();
      });
    
      it('XXX', done => {
        const transport = {
          sendMail: (data, callback) => {
            const err = new Error('some error');
            callback(err, null);
          }
        };
        sandbox.stub(nodemailer, 'createTransport').returns(transport);
    
        // CALL FUNCTION TO TEST
    
        // EXPECT RESULT
      });
    });
    

提交回复
热议问题