K. D.
K. D.

Reputation: 4219

grunt + mochaTest: Change working directory?

I`m trying to implement testing for my nodejs-project with grunt-mocha-test and have issues with different/incorrect paths.

Like I saw it elsewhere, I want to get all dependecies by just requiring my server.js.

gruntfile.js

mochaTest: {
  test: {
    options: {
      reporter: 'spec',
      require: 'app/server.js'
    },
    src: ['app/test/**/*.js']
  }
}

My current project structure looks like this

gruntfile.js
app/server.js
app/models/..
app/controllers/..
app/tests/..

users.controller.test.js

var userCtl = require('../controllers/users.controller');

describe("return5", function () {
  it("should return 5", function () {
    var result = userCtl.return5(null, null);
    expect(result).toBe(5);
  });
});

users.controller.js

var mongoose = require('mongoose');
var User = mongoose.model('User'); // <- Mocha crash: Schema hasn't been registered for model "User".
..

In my server.js I use:

..
// config.js: https://github.com/meanjs/mean/blob/master/config/config.js
config.getGlobbedFiles('./models/**/*.js').forEach(function (path) {
  require(path); // never called with mochaTest
});
..
console.log(process.cwd()); // "C:\path\project" (missing /app)
..

So the cwd is different to what it should be.

Can someone please help me getting around this issue?

I will clarify the title as soon as I know what I`m doing wrong.

Thank you.

Upvotes: 3

Views: 2069

Answers (1)

Louis
Louis

Reputation: 151380

The confusion is due to the difference between module paths and filesystem paths.

When you do require("./blah"), the . is interpreted to mean "start with the path of the current module". Since this is relative to the module you are currently in, it will resolve to different values depending on where the module is located.

When you run process.cwd() this is returning the current working directory of the process. This does not change from module to module. It changes when your code calls process.chdir(). Also, when you perform filesystem operations that use ., this is interpreted relative to process.cwd().

So that you get C:\path\project from process.cwd() is not surprising since this is where you'd typically run Grunt (i.e. at the top level of your project). What you can do if you want paths relative to a module is use __dirname. For instance, this code reads files from a foo subdirectory in the same location where the module that contains this code is located:

var path = require("path");
var fs = require("fs");

var subdir = path.join(__dirname, "foo");
var foofiles = fs.readdirSync(subdir);

Upvotes: 3

Related Questions