Mocking modules in Node.js for unit testing

I recommend proxyquire.

It does what you want to achieve, while not relying on dependency injection, which is obtrusive for your code and requires code changes if you didn't write your modules in that fashion.


I am using mocha as the test framework and sinon for mocking, stubing and spying. I would suggest you delegate your account module to the auth.coffee module and mock it like so:

exports.init = function (account) {
    // set account object
}

so from the mocha test you can then create a dummy account object and mock it with sinon in the actual test.

describe('some tests', function () {

    var account, response, testObject;

    beforeEach(function () {

        account = {
             register: function () { }
        };

        response = {
            send: function () { }
        };

        testObject = require('./auth');
        testObject.init(account);
    });

    it('should test something', function () {

        var req = { body: { email: ..., password: .... } }, // the request to test
            resMock = sinon.mock(response),
            registerStub = sinon.stub(account, 'register');

        // the request expectations
        resMock.expect('send').once().withArgs(200);

        // the stub for the register method to have some process
        registerStub.once().withArgs('someargs');

        testObject.auth(req. response);

        resMock.verify();

    });

});

Sorry for not writing it down in coffescript but I am not used to it.