0

I am programming some mock server test cases for a program I am working on and have encountered an issue that i am unfamiliar with.

Here is the simple rest server

var restify = require('restify');
var server = restify.createServer();

var mock = {};
module.exports = mock;
var resp = '';
mock.init = function(name, port,callback) {
    resp = name;
    server.use(restify.bodyParser({
        mapParams: false
    }));

    server.get('/ping', function(req, res, next) {
        res.send(resp);
    });
    server.listen(port, function() {
        console.log('%s listening at %s', server.name, server.url);
        callback(undefined,server.url);
    });
};

and I try to initialize two servers with:

var should = require('should');

var mock1 = '';
var mock2 = '';

describe('mock riak load balancer', function() {
    it('should configure a mock riak node', function(done) {
        mock1 = require('./mock.js');
        mock1.init('mock1', 2222, function(e, r) {
            done();
        });
    });
    it('should configure a second mock riak node', function(done) {
        mock2 = require('./mock.js');
        mock2.init('mock2', 2223, function(e, r) {
            done();
        });
    });
});

Unfortunately I get a connection refused when I ping mock1, so it's being overwritten by the second call. Guessing this has something to do with the way Javascript handles scoping, but I am not sure.

I resorted to this: https://gist.github.com/hortinstein/5814537 but I think there has to be a better way

Hortinstein
  • 2,667
  • 1
  • 22
  • 22

1 Answers1

1

it has to do with the way node.js loads modules. node.js caches required modules in your process, which means the mock2 is basically the same object as mock1.

more info:

Community
  • 1
  • 1
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
  • great links, any idea how to better do what I have resorted to here (for my mock code) https://gist.github.com/hortinstein/5814537 – Hortinstein Jun 19 '13 at 13:59
  • take a look at [rewire](https://npmjs.org/package/rewire), a dependency injection module for creating mocks, which are really mocks – hereandnow78 Jun 20 '13 at 06:24