I'm trying to pass the grep argument so that the karma-mocha plugin will pass it to Mocha and run only the tests that match grep. The command line is like this:
./node_modules/.bin/karma run -- --grep='one'
However, Karma actually goes over all tests, in exactly the same way as if I do not use --grep. According to karma run --help, everything after -- should be client arguments. (It is referred to as clientArg in the help and in discussions about how to run karma run.) I tried a small project without RequireJS and it worked. It seems that adding RequireJS causes a problem. Here is a small setup that reproduces the issue:
karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs'],
files: [
'test-main.js',
{ pattern: 'test/**/*.js', included: false }
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
});
};
test-main.js:
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
Object.keys(window.__karma__.files).forEach(function (file) {
if (TEST_REGEXP.test(file)) {
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
baseUrl: '/base',
deps: allTestFiles,
callback: window.__karma__.start
});
What you see here is functionally equivalent to the stock test-main.js that was initially generated by karma init. It was only edited to remove comments, normalize space, and add semi-colons.
The test/test.js file contains:
it("one", function () {});
it("two", function () {});
Explanation
This is a problem with how
karma initgenerates thetest-main.jsfile that is used to configure RequireJS and kick off the test. The issue is not specific to Mocha but would most likely happen with other runners that accept parameters passed throughclientArgs.The
test-main.jsgenerated bykarma initis actually broken. You can see here that when Karma callsstartby itself, it calls it with its own configuration:However, the
test-main.jscreated bykarma initcallsstartwithout any argument, and this is why your plugin is not getting the arguments that it should be getting.Solution
Modify your
test-main.jsto have thiscallbackin your RequireJS config:This will cause
startto be called in the same way as it is in the code snippet shown earlier. If for some reason you do not likebindor need to do more in your callback, you could do: