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

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

great links, any idea how to better do what I have resorted to here (for my mock code) gist.github.com/hortinstein/5814537
take a look at rewire, a dependency injection module for creating mocks, which are really mocks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.