javascriptnode.jsswaggerproxyquireswagger-node-express

How to bind a helper stub to swagger-node with supertest?


I am using Swagger Node with express and I initialized the skeleton project. Swagger project create hello-world

Then inside the hello-world/api/controllers/hello_world.js I added a small modification to require a helper hello_helper.js and call its function helloHelper.getName().

'use strict';
let helloHelper = require('../helpers/hello_helper');
var util = require('util');
module.exports = {
  hello: hello
};
function hello(req, res) {
  var name = req.swagger.params.name.value || helloHelper.getName();
  var hello = util.format('Hello, %s!', name);
  res.json(hello);
}

hello-world/api/helpers/hello_helper.js

'use strict';
module.exports = {getName: getName};
function getName() {
    return 'Ted';
}

I would like to stub helloHelper.getName() to return 'Bob' instead. I can do so easily with: hello-world/test/api/controllers/hello_world.js

// Create stub import of hello_helper
mockHelloHelper = proxyquire('../../../api/controllers/hello_world', { '../helpers/hello_helper': { getName: function () { return 'Bob'; } }
});

Using supertest how can I make swagger recognize my stub?

EDIT: Thanks to help from the answer below this solution worked for me.

var app, getNameStub, mockHelloHelper, request;
    beforeEach(function (done) {
       // Create stub import of hello_helper
        mockHelloHelper = proxyquire('../../../api/controllers/hello_world', {
           '../helpers/hello_helper': {
               getName: function () {
                   return 'Bob';
               }
           }
        });
        app = require('../../../app');
        request = supertest(app);
        done();
    });
...
it('should return a default string', function(done) {
        request
          .get('/hello')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200)
          .end(function(err, res) {
            should.not.exist(err);
            res.body.should.eql('Hello, Bob!');
            done();
          });
      });

Solution

  • You need to initialize/require express app after you have proxyquired your dependency. Only then it can use your stubbed version of getName:

    beforeEach(function () {
        mockHelloHelper = proxyquire('../../../api/controllers/hello_world', {
           '../helpers/hello_helper': {
               getName: function () {
                   return 'Bob';
               }
           }
        });
        // initialize/require your app here
        request = supertest(app);
    });