Search code examples
javascriptnode.jsjasminejasmine-node

Check for node modules being loaded using jasmine-node


So I'm trying to teach myself Jasmine (for node) by working through a tutorial for a Mongoose project, TDD style, writing tests for what each step is supposed to accomplish, then following the actual tutorial, etc.

Of course, my first test is failing.

app.js at this point is two lines:

var mongoose = require('mongoose');
console.log(mongoose.version);

This runs fine. My test however, still fails:

var app = require('../src/app.js');

describe('App startup', function() {
    it('loads mongoose', function() {
            expect(app.mongoose.version).toBeDefined();
    });
    it('loads jasmine-jquery', function() {
            expect($).toBeDefined();
    });
});

Results in

Failures:

1) App startup loads mongoose
Message:
 TypeError: Cannot read property 'version' of undefined
Stacktrace:
 TypeError: Cannot read property 'version' of undefined
at null.<anonymous> (/home/jbhelfrich/mongooseBlog/spec/init.spec.js:5:36)

(The jquery test is, of course, expected to fail still at this point.) I've tried it with and without the 'app.' in the expect clause, but I get the same error--the test suite doesn't see the internals of app.js. But I know it's loading the app.js file correctly, because it's running it--the console.log output appears ahead of the test results.

So I suspect I've misunderstood something fundamental about scope, or some other rookie mistake, but I'm not sure what that is.


Solution

  • Node.js is structured into modules. If you want a a module's properties to be accessible, that module's properties must be defined in the module.exports variable. This is what an export might look like (note that exports references module.exports):

    var mongoose = require('mongoose');
    console.log(mongoose.version);
    exports.mongoose = mongoose;
    

    Then when you've used require() on a file with the code shown above, the variables will be set, where app is equivalent to module.exports in the module that is being loaded:

    var app = require('../src/app.js');
    console.log(app.mongoose.version);