Karma and RequireJS: avoid duplication in src and check your RequireJS configuration

For example, this test-main.js , and this main.js have duplicate paths and shims. For large projects, there can be many. I can even use the grunt-bower-requirejs plugin to add installed Bower components to main.js, but after that I need to copy them to test-main.js, either manually or by a program.

Is there a convenient way to avoid this duplication, for example, tell RequireJS to include another configuration file?

+7
javascript requirejs karma-runner
source share
1 answer

I also hate duplicate information. I am working on this issue using an HTML setting in my test case that calls require.config twice.

So, the HTML in my test suite first loads RequireJS, and then the general configuration, which is in a file called requirejs-config.js :

 <script type="text/javascript" src="lib/requirejs/require.js"></script> <script type="text/javascript" src="requirejs-config.js"></script> 

The requirejs-config.js nothing special. Here's a shortened version:

 require.config({ baseUrl: 'lib/', paths: { browser_test: '../../../browser_test', jquery: 'external/jquery-1.10.2', bootstrap: 'external/bootstrap/js/bootstrap.min', // [...] }, packages: [ { name: "lodash", location: "external/lodash" } ], shim: { bootstrap: { deps: ["jquery"], exports: "jQuery.fn.popover", }, // [...] }, config: { // [...] }, enforceDefine: true }); 

Then there is a <script> element that calls require.config with the settings that apply to the test environment:

 <script> require.config({ paths: { 'mocha': '/node_modules/mocha', 'chai': '/node_modules/chai/chai' }, shim: { 'mocha/mocha': { exports: "mocha", init: function () { this.mocha.setup('bdd'); return this.mocha; } } }, config: { // [...] } }); </script> 

(The 'mocha/mocha' looks ridiculous, but right.)

In this particular case, the second call to require.config only adds new values ​​to paths , shim and config , but you can also override earlier values. I could, for example, change the path where 'jquery' resolves or resizes the Bootstrap block.

You can see that I am using Mocha + Chai for my test suite, but the above solution is really not specific to Mocha at all.

+5
source share

All Articles