-->

Testing CommonJS modules that use browserify alias

2019-06-02 05:18发布

问题:

Browserify allows creating aliases and shimming modules that are not directly CommonJS compatible. Since I'd like to run my tests in node CLI, can I somehow handle those aliases and shimmed modules in node?

For example, let's say I'm aliasing ./my-super-module to supermodule and shimming and aliasing some jquery plugin ./vendor/jquery.plugin.js -> ./shims/jquery.plugin.shim.js to jquery.plugin.

As a result, I can do this in my module:

var supermodule = require('supermodule');
require('jquery.plugin');

// do something useful...
module.exports = function(input) {
  supermodule.process(output)
}

Are there any practices how I could test this module in node.js/cli so that the dependencies are resolved?

回答1:

You might want to use proxyquire if you plan to test this module directly in node using any cli runner.

using mocha will be something like this

describe('test', function () {
  var proxyquire = require('proxyquire').noCallThru();
  it('should execute some test', function () {
     var myModule = proxyquire('./my-module', {
         // define your mocks to be used inside the modules
        'supermodule' : require('./mock-supermodule'),
        'jquery.plugin': require('./jquery-plugin-mock.js')
     });
  });
});

If you want to test this is a real browser, you might not need to mock your aliases modules, you can use browserify to run your tests in karma directly.

If you need to mock modules in that scenario you can use proxyquireify, which will allow you to do the same but with browserify.

there is also browsyquire which is a fork of proxyquireify that I made with some extra features and a bug fix.