Search code examples
javascriptnode.jsunit-testingkarma-runnerbrowserify

Karma: Cannot find module in relative path


I have a hard time with Karma not being to load a specific file. I am a beginner regarding Karma, I however spend the entire day diving into the documentation and looking for similar issues without success.

When starting the karma process, it will fail when loading a config file. Here is the error:

Chrome 52.0.2743 (Linux 0.0.0) ERROR
Uncaught Error: Cannot find module './development'
at /tmp/node_modules/browser-pack/_prelude.js:1:0 <- /tmp/7b47eeb55cec3f8cc510b5cd637c570a.browserify:1

I do not suspect the file to be the issue itself. My guess would be that the issue is around the 'require' action. This file is probably the first one to be 'required' during the execution. So Browserify could also be guilty.

files tree:

.
├── karma.conf.js
├── LICENSE
├── package.json
├── README.md
└── src
    ├── config
    │   ├── base.js
    │   ├── development.js
    │   ├── index.js
    │   └── production.js
    ├── controllers
    │   ├── authentication.js
    │   └── __test__
    │       └── authentication.test.js
    ├── modules
    │   └── auth
    │       ├── builder.js
    │       └── __test__
    │           └── mocks
    │               └── builder.mock.js
    ├── router.js
    └── server.js

karma.conf.js

'use strict';
module.exports = function(config) {

  config.set({

    basePath: '',
    frameworks: ['mocha', 'sinon-chai', 'browserify'],
    files: [
      'src/**/*.test.js'
    ],
    exclude: [
    ],
    preprocessors: {
      'src/**/*.test.js': ['browserify']
    },
    reporters: ['progress', 'mocha'],
    browserify: {
      debug: true,
      transform: [
        ['babelify',{
          presets: ['es2015'],
        }]
      ]
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
}

Fails in src/config/index.js

'use strict';

const env = process.env.NODE_ENV || 'development';
const config = require('./' + env);

module.exports = config;

In order to give you guys a way to reproduce it, i built a small node application: https://github.com/slecorvaisier/karma-starterkit

Start with:

 npm run test

Versions: node-v: v6.2.0 npm -v: 3.8.9

Thanks a lot in advance for any help.


Solution

  • I think the problem comes from your usage of require with variables, which is not supported in browserify.

    Instead of writing :

    const env = process.env.NODE_ENV || 'development';
    const config = require('./' + env);
    

    try :

    const config = process.env.NODE_ENV === "production" ? require('./production') : require('./development');
    

    The rule is that you can't use anything variable inside require.

    Also see Why can I not use a variable as parameter in the require() function of node.js (browserify)?