简体   繁体   中英

Testing CommonJS modules that use browserify aliases and shims

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?

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 .

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