Search code examples
unit-testingmocha.jsbrowserifygulp-mocha

Absolute Paths with Gulp Mocha and Browserify


I have a project which is using Browserify and ES6 to handle importing and defining packages. The project is using absolute paths using the 'paths' option when building with Gulp-Browserify.

This works fine for the source code, but now I am attempting to write tests with Mocha and run them using gulp-mocha and this is causing problems. Mocha is expecting relative paths, but if I give it a relative path to a file that has other imports using absolute paths, testing will fail with a MODULE_NOT_FOUND error.

for example

Mocha Import at test/actions/user.js:
      import createUser from '../../src/actions/user';
      ...

Source Import at src/actions/user.js:
      import CREATE_USER from 'constants/use
      ...

will cause a MODULE_NOT_FOUND_ERROR

What I'm wondering is if there is any way to set an absolute path list in mocha similar to how you can for browserify?


Solution

  • You can use app-require-path. Just install it as a dev dep and add the following two files:

    test/mocha.opts

    --require test/_bootstrap.js
    

    test/_bootstrap.js

    require('app-require-path')(__dirname + '/..');
    

    And that's it. You can change the path in _bootstrap.js to whatever you want. You can also add multiple paths. It's up to you.