Testing CommonJS modules that use browserify aliases and shims

前提是你 提交于 2019-12-10 11:42:08

问题


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.



来源:https://stackoverflow.com/questions/23597469/testing-commonjs-modules-that-use-browserify-aliases-and-shims

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!