简体   繁体   中英

Mocha tests: avoid '../../' when requiring

My folder structure is:

/backend/services/service.js
/test/backend/services/service.js

In each service test, I use the following:

var service = require('../../../backend/services/service')

Is there a more elegant way of automatically requiring the file with the same path, only without the test folder? Maybe using mocha.opts somehow?

I can give you a solution a little hacky that I use. I have a /test/__bootstrap.test.js file where I create a global testRequire() function that I only use for tests:

// Creation of a wrapper to avoid ../../../.. using require()
global.testRequire = function(name) {
  return require(path.join(__dirname, '..', name));
};

Then in /test/backend/services/service.js I use testRequire() instead of require() .

var service =  = testRequire('backend/services/service');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM