简体   繁体   中英

Stubbing a constructor of a third party library when testing express app with Supertest

I've got a simple express app that looks like this:

var SendMandrillTemplate = require('send-mandrill-template');
var sendMandrillTemplate = new SendMandrillTemplate('api-key-goes-here');

var app = require('express')();

app.get('/', function(req, res, next) {

    sendMandrillTemplate.sendTemplate(
        'template-name-goes-here',
        'email@here.com', {
            value: 123
        },
        function(err) {
            if (err) {
                res.send('ERR - ', err)
            } else
                res.send('DONE')
        });
});

module.exports = app;

I export the app object, so I can mount this in a separate server.js like this -

var app = require('./app')

app.listen(1234, function() {
    console.log('Running on port 1234');
});

This is to enable me to use supertest a bit easier.

Here's my test so far:

var app = require('./app')
var request = require('supertest')

var SendMandrillTemplate = require('send-mandrill-template');

describe('GET /', function() {

    var sendTemplateStub;
    before(function() {
        //I think i need to setup a spy on the created instance of SendMandrillTemplate.sendTemplate
        //sendTemplateStub = //?
    });

    it('calls sendTemplate on sendMandrillTemplate instance', function(done) {
        request(app)
            .get('/')
            .expect(200)
            .end(function(err, res) {
                if (err) throw err;

                //assert sendTemplateStub was called with 'template-name-goes-here'
                //etc...

                done();
            })
    })
})

As you can see, I'm having trouble stubbing the SendMandrillTemplate constructor

If I wasn't newing up an instance of SendMandrillTemplate I could do something like:

sendTemplateStub = sinon.stub(SendMandrillTemplate, 'sendTemplate')

But of course, in this scenario this won't work...

You can get away with something as simple as

var SendMandrillTemplate = require('send-mandrill-template');
sinon.stub(SendMandrillTemplate.prototype, 'sendTemplate');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM