Mocha unit tests running with Karma - done() is not defined - javascript

I'm trying to get tests written with Mocha to work running Karma, and they sort of work, but I cannot use the done() method to implement async tests, which essentially makes the tools useless to me. What am I missing?
karma.conf.js
module.exports = function(config) {
config.set({
basePath: '../..',
frameworks: ['mocha', 'requirejs', 'qunit'],
client: {
mocha: {
ui: 'bdd'
}
},
files: [
{pattern: 'libs/**/*.js', included: false},
{pattern: 'src/**/*.js', included: false},
{pattern: 'tests/mocha/mocha.js', included: false},
{pattern: 'tests/should/should.js', included: false},
{pattern: 'tests/**/*Spec.js', included: false},
'tests/karma/test-main.js'
],
exclude: [
'src/main.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'dots'],
port: 9876,
colors: true,
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_WARN,
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
test-main.js (configuring RequireJS)
var allTestFiles = [];
var pathToModule = function(path) {
return path.replace(/^\/base\//, '../').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (/Spec\.js$/.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/src',
paths: {
'should': '../tests/should/should',
'mocha': '../tests/mocha/mocha',
'pubsub': '../libs/pubsub/pubsub',
'jquery': '../libs/jquery/jquery-1.10.2',
'jquery-mobile': '//code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min'
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
tests/fooSpec.js
define(['music/note'], function(Note) {
describe('nothing', function(done) {
it('a silly test', function() {
var note = new Note;
note.should.not.eql(32);
});
done();
});
...
Though this is a contrived example, it succeeds if I remove the done() call. As it is, I get:
Uncaught TypeError: undefined is not a function
at /Library/WebServer/Documents/vg/tests/mocha/fooSpec.js:8
This is the done() line. How/why is this not defined? I'm not understanding where else to configure Mocha (or with what options). Is there some sort of global namespace or meta-programming magic causing RequireJS to interfere with Mocha?
I'm running the tests in Chrome 33 on OS X 10.9.2, in case that is at all relevant. I've killed a ton of time on this and am ready to give up on automated testing :( -- had similar brick walls with QUnit/Karma/RequireJS and have not been able to find any alternative to successfully automate tests. I feel like an idiot.

In Mocha, the done callback is for it, before, after, beforeEach, afterEach. So:
describe('nothing', function() {
it('a silly test', function(done) {
var note = new Note;
note.should.not.eql(32);
done();
});
});
Here's the doc.

The test you are running in that example doesn't require the done() callback. It is not asynchronous. An example of when the done callback is need....
describe('Note', function() {
it('can be retrieved from database', function(done) {
var note = new Note();
cb = function(){
note.contents.should.eql("stuff retrieved from database");
done()
}
//cb is passed into the async function to be called when it's finished
note.retrieveFromDatabaseAsync(cb)
});
});
Your test should not have a done callback
describe('nothing', function() {
it('umm...', function() {
var note = new Note;
note.should.not.eql(32);
});
});
Only the 'it' function provides a done callback. describe does not. Your problem does not rest with karma. Your mocha tests are not defined correctly.

Holy %$##!
I would never in a million years have thought this would barf:
describe('nothing', function(done) {
it('umm...', function() {
var note = new Note;
note.should.not.eql(32);
});
done(); // throws error that undefined is not a function
});
But this works just fine:
describe('nothing', function(done) {
it('umm...', function() {
var note = new Note;
note.should.not.eql(32);
});
setTimeout(function() {
done(); // MAGIC == EVIL.
}, 1000);
});

Related

Karma/Istanbul Code Coverage does not find functions and always returns 100%

I am attempting to add Code Coverage for my Karma tests, however although it finds the correct JS files that I'm testing, it does not find the functions inside those files.
From what I have read so far I believe it to be to do with the files not being correctly browserified before being passed to istanbul to do the coverage, but admittedly I am new to this so I'm hoping for some suggestions.
Here is my JS file(common.js):
var applicationSettings = require('./settings');
var common = {
getAjaxBaseUrl: function () {
var strVirtualDirectory = applicationSettings.VirtualDirectory;
if (strVirtualDirectory.length > 1) {
if (!strVirtualDirectory.startsWith("/")) {
strVirtualDirectory = "/" + strVirtualDirectory;
}
}
return strVirtualDirectory;
}
}
module.exports = common;
And here are the tests I have written:
it('Client - Should get correct AjaxBaseUrl with /', function () {
var clientSettings = require('./../client/scripts/settings');
var clientCommon = require('./../client/scripts/common');
clientSettings.VirtualDirectory = '/VD';
expect(clientCommon.getAjaxBaseUrl()).to.equal('/VD');
});
it('Client - Should get correct AjaxBaseUrl without /', function () {
var clientSettings = require('./../client/scripts/settings');
var clientCommon = require('./../client/scripts/common');
clientSettings.VirtualDirectory = 'VD';
expect(clientCommon.getAjaxBaseUrl()).to.equal('/VD');
});
My Karma.conf is below:
// Karma configuration
// Generated on Mon Jan 11 2016 09:43:00 GMT+0000 (GMT Standard Time)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['phantomjs-shim', 'browserify', 'mocha'],
// list of files / patterns to load in the browser
files: [
'https://code.jquery.com/jquery-2.2.0.min.js',
'http://cdn.kendostatic.com/2015.3.1111/js/kendo.all.min.js',
'test_unit/*Spec.js',
'client/scripts/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test_unit/*Spec.js': ['browserify'],
'client/scripts/*.js': ['browserify', 'coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage', 'junit'],
// Configure jUnit reporter
junitReporter: {
outputDir: '', // results will be saved as $outputDir/$browserName.xml
outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile
suite: '', // suite will become the package name attribute in xml testsuite element
useBrowserName: true // add browser name to report and classes names
},
// Configure coverage reporter
coverageReporter: {
type: 'html',
dir: 'test_coverage',
subdir: '.',
file: 'coverage.htm'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
browserify: {
configure: function (bundle) {
bundle.transform('reactify', { extensions: ['.jsx'] });
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
})
}
This does produce a report, but this shows 100% and the only line found in the common.js file is:
require("C:\\Source\\ProjectName\\client\\scripts\\common.js");
I attempted to add Browerify-Istanbul into the mix, by adding a require for it at the top of the Karma.conf an additional transform in the browserify section
bundle.transform(istanbul)
However this just makes my tests fail and throw several errors:
undefined is not an object (evaluating
'__cov_qQLFhXEMt7fatxiMx0_vQQ.b[' 1'][0]')
getAjaxBaseUrl#C:/Users/CHARLE~1.WIC/AppData/Local/Temp/0d61da722d2838c9
600d83d1cbb4c0b8.browserify:43:1498
C:/Users/CHARLE~1.WIC/AppData/Local/Temp/0d61da722d2838c9600d83d1cbb4c0b
8.browserify:51742:1849
16 02 2016 09:14:08.515:ERROR [coverage]: [TypeError: Cannot read
property 'star t' of undefined] TypeError: Cannot read property
'start' of undefined
at C:\Source\ProjectName\node_modules\istanbul\lib\o bject-utils.js:59:44
at Array.forEach (native)
at Object.addDerivedInfoForFile (C:\Source\ProjectName\node_modules\istanbul\lib\object-utils.js:58:37)
at Object.Collector.fileCoverageFor (C:\Source\ProjectName\node_modules\istanbul\lib\collector.js:94:15)
at C:\Source\ProjectName\node_modules\istanbul\lib\r eport\html.js:558:90
at Array.forEach (native)
at HtmlReport.Report.mix.writeReport (C:\Source\ProjectName\node_modules\istanbul\lib\report\html.js:557:27)
at writeReport (C:\Source\ProjectName\node_modules\k arma-coverage\lib\reporter.js:62:16)
at C:\Source\ProjectName\node_modules\karma-coverage \lib\reporter.js:288:11
at C:\Source\ProjectName\node_modules\karma\lib\help er.js:82:7
at FSReqWrap.oncomplete (fs.js:82:15)
Am I missing something, or going about this the wrong way?
I had the exact same issue. What worked for me was removing "coverage" from the preprocessors section AND using browserify-istanbul. Also, you want to configure browserify-istanbul to ignore your test files.
So your preprocessors should look something like (removed 'coverage'):
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test_unit/*Spec.js': ['browserify'],
'client/scripts/*.js': ['browserify']
},
And your browserify config should look something like:
browserify: {
configure: function (bundle) {
bundle.transform('reactify', { extensions: ['.jsx'] });
bundle.transform(require('browserify-istanbul')({
ignore: ['**/test_unit/**']
}));
}
},
Hope that helps
For me the solution was to:
delete 'coverage' in the array of values of *.js files from preprocessors index into karma.conf
Hope that helps

Testing services from $resource using factory with Karma

I'm new to karma and I'm trying to run tests in order to check if my factories are set to the proper value returned by the API.
apiServices.js :
'use strict';
angular.module('balrogApp.services', ['balrogApp.config'])
.factory('Requests', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/requests/:id', {id: '#id'});
}])
.factory('Projects', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/projects/:id', {id: '#id'}, {'update': { method:'PUT' }});
}])
.factory('Users', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
return $resource(balrogConfig.backend + '/users/:id', {id: '#id'});
}]);
config.js :
'use strict';
angular.module('balrogApp.config', [])
.constant('balrogConfig', {
'backend': 'http://127.0.0.1:8000/api/catalog'
});
Now, I've been through a few articles about $resource and karma but I didn't really get how to set up the unit tests for my case.
Here is my test file : (edited after #Freezystem answer)
describe("Services test", function () {
var Requests, Projects, Users;
beforeEach(function () {
angular.mock.module("balrogApp.services");
angular.mock.inject(function (_Requests_, _Projects_, _Users_) {
Requests = _Requests_;
Projects = _Projects_;
Users = _Users_
});
});
it("API factories must be defined", function () {
expect(Requests).toBeDefined();
expect(Projects).toBeDefined();
expect(Users).toBeDefined();
});
});
I also tried a few things with $httpBackend but couldn't make it neither.
How to make this work in order to know if the services are working.
Also, how to check if the services are returning the expected response from the API ?
Edit : Adding karma.conf.js :
// Karma configuration
// Generated on Tue Nov 17 2015 13:48:48 GMT+0100 (Romance Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-aria/angular-aria.js',
'bower_components/angular-material/angular-material.js',
'bower_components/angular-messages/angular-messages.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'bower_components/ui-select/dist/select.js',
'bower_components/angular-smart-table/dist/smart-table.js',
'bower_components/angular-ui-switch/angular-ui-switch.js',
'bower_components/angular-growl-v2/build/angular-growl.js',
'bower_components/angular-number-picker/angular-number-picker.js',
'bower_components/moment/moment.js',
'app/*.js',
'app/**/*.js',
'tests/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
};
So far, I'm getthing this error : http://codepen.io/anon/pen/OyqWdE
Just try to inject each factory by its own name :
describe("Services test", function () {
var users, $httpBackend;
beforeEach(function(){
angular.mock.module('balrogApp.services');
angular.mock.inject(function (_Users_, _$httpBackend_) {
users = _Users_;
$httpBackend = _$httpBackend_;
});
});
// clear all outstanding requests after each tests
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Factories must be defined", function () {
// simulate API response
$httpBackend.when('/api/catalog/users/1337')
.respond( 200, { id : 1337, name : 'Tom' } );
// there is a better way to do it actually but I'm unable to make it work
// $httpBackend.whenRoute('GET', '/api/catalog/users/:id')
// .respond(function ( method, url, data, headers, params ) {
// return [ 200, { user : params.id } ] ;
// });
// make the user request to the API
var user = users.get({id:1337});
$httpBackend.flush();
// test API returned Object
expect(user.id).toBe(1337);
expect(user.name).toBe('Tom');
});
});
Let me know if you have any other questions.

error with mocha karma test runner

My directory structure is:
karma.conf.js
GruntFile.js
src
-MyModule.js
lib
-bar.js
test
-MyModule.test.js
-test-main.js
This is my karma.conf.js file
// Karma configuration
// Generated on Sat Aug 08 2015 08:09:40 GMT+0530 (IST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'requirejs','chai'],
// list of files / patterns to load in the browser
files: [
{pattern: 'lib/**/*.js', included: false},
{pattern: 'src/**/*.js', included: false},
{pattern: 'test/**/*.test.js', included: false},
'test/test-main.js',
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
this is lib/bar.js
module.exports = function (a, b) {
return a+b;
}
this is src/MyModule.js
var bar = require("../lib/bar.js");
module.exports={
add:function add (a, b) {
return bar(a, b);
}
}
and this is test/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',
paths: {
'../src/MyModule.js': '../src/MyModule.js',
'../lib/bar.js': '../lib/bar.js'
},
deps: allTestFiles,
callback: window.__karma__.start
});
and this is the test/MyModule.test.js
var MyModule = require('../src/MyModule.js');
describe('A test suite', function () {
var expect = window.expect;
beforeEach(function () {
});
afterEach(function () {
});
it('should add the two numbers', function () {
var abc = MyModule.add(1, 3);
expect(abc).to.be.equal(4);
});
});
When I am running the test I get the error
Error: Module name "../src/MyModule.js" has not been loaded yet for context: _. Use require([])
where am I going wrong?
the function add() somehow needs be accessible from within the local scope of the test, eg.:
describe('A test suite', function() {
/* ... */
var add = function(a, b) {return a+b;};
/* ... */
});
alternatively, the require() function can be used to load further scripts.

Karma unit test tries to send a request to a completely different module

I have the following karma test for the angular-fullstack scaffold:
describe('Directive: categoryLookAhead', function () {
// load the directive's module and view
beforeEach(module('portfolioApp'));
beforeEach(module('app/article/Directives/categoryLookAhead/categoryLookAhead.html'));
var element, scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<category-look-ahead></category-look-ahead>');
element = $compile(element)(scope);
scope.$apply();
expect(element.text()).not.toBe(null);
}));
});
and this is my karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'client/bower_components/jquery/dist/jquery.js',
'client/bower_components/angular/angular.js',
'client/bower_components/angular-mocks/angular-mocks.js',
'client/bower_components/angular-resource/angular-resource.js',
'client/bower_components/angular-cookies/angular-cookies.js',
'client/bower_components/angular-sanitize/angular-sanitize.js',
'client/bower_components/angular-route/angular-route.js',
'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'client/bower_components/lodash/dist/lodash.compat.js',
'client/bower_components/angular-socket-io/socket.js',
'client/bower_components/angular-ui-router/release/angular-ui-router.js',
'client/bower_components/angular-markdown/angular.markdown.js',
'client/bower_components/angular-ui-router-title/angular-ui-router-title.js',
'client/app/app.js',
'client/app/app.coffee',
'client/app/**/*.js',
'client/app/**/*.coffee',
'client/components/**/*.js',
'client/components/**/*.coffee',
'client/app/**/*.jade',
'client/components/**/*.jade',
'client/app/**/*.html',
'client/components/**/*.html'
],
preprocessors: {
'**/*.jade': 'ng-jade2js',
'**/*.html': 'html2js',
'**/*.coffee': 'coffee',
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/'
},
ngJade2JsPreprocessor: {
stripPrefix: 'client/'
},
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
and this is the directive's controller:
angular.module('portfolioApp')
.directive('categoryLookAhead', function($interval, $filter) {
return {
templateUrl: 'app/article/Directives/categoryLookAhead/categoryLookAhead.html',
restrict: 'E',
scope: {
suggestedTags: '=',
selectedTags: '='
},
...
In my head, it should just compile from that template and start doing its thing but I get an error:
Error: Unexpected request: GET app/main/main.html
main.html does not include this directive at all, so I don't know why it's getting an unexpected request for this.
I've read in other StackOverflow posts that I can use whenGET(*).passThrough() to ignore these things, but I'd like to know why it's making a request to a module that has nothing to do with the directive.

"Uncaught TypeError: Cannot read property '...' of null" using RequireJS with Karma

I'm trying to get Jasmine tests running in Karma. This is for an AngularJS app using RequireJS, but for now, the test is a simple expect(true).toBe(true); test with no Angular dependencies. I've found that it runs when I disable Karma's requirejs module and comment-out "client/app/require-shared.js" and "test/require-test.js" in files and load the testSpec.js file directly.
However, as soon as I re-enable requirejs and add the RequireJS config files back to karma.conf.js's files--keeping the testSpec.js file there to be loaded "statically"--I see the errors
Chrome 33.0.1750 (Windows 7) ERROR
Uncaught TypeError: Cannot read property 'failedCount' of null
at C:/.../project/node_modules/karma-jasmine/lib/adapter.js:126
Chrome 33.0.1750 (Windows 7) ERROR
Uncaught TypeError: Cannot read property 'length' of null
at C:/.../project/node_modules/karma-jasmine/lib/jasmine.js:2518
Chrome 33.0.1750 (Windows 7): Executed 1 of 2 ERROR (0.009 secs / 0.001 secs)
If I try the full Angular test, I get errors about $injector being null, but I think it's all rooted in this requirejs module issue. What am I missing in my setup to make this work?
test/karma.conf.js
module.exports = function(config) {
config.set({
basePath: "../", // resolves to "project/"
frameworks: ["jasmine", "requirejs"],
files: [
// load the RequireJS config files first
"client/app/require-shared.js",
"test/require-test.js",
// set included to false for files to be loaded via RequireJS
// {pattern: "bower_components/**/*.js", included: false},
// {pattern: "client/**/*.js", included: false},
// {pattern: "test/unit/*Spec.js", included: false}
{pattern: "test/unit/*Spec.js"}
],
// list of files to exclude
exclude: [
// "client/app/app.js",
// "client/app/bootstrap.js",
// "client/app/require-main.js",
"*.conf.js"
],
reporters: ["progress"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ["Chrome"],
singleRun: true
});
};
client/app/require-shared.js
requirejs.config({
paths: {
"app": "../app/app",
"angular": "../extlibs/angular-1.2.14",
"jquery": "../extlibs/jquery-2.1.0.min",
"ng-cookies": "../extlibs/AngularPlugins/angular-cookies-1.2.13",
"ng-resource": "../extlibs/AngularPlugins/angular-resource-1.2.13",
"ng-route": "../extlibs/AngularPlugins/angular-route-1.2.14",
}
,shim: {
angular: {
exports: "angular"
}
,"ng-resource": {
deps: [ "angular" ],
exports: "ng-resource"
},
,"ng-cookies": ["angular"]
,"ng-route": ["angular"]
,"ngui-bootstrap": ["angular"]
}
});
test/require-test.js
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, "").replace(/\.js$/, "");
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
var normalPath = pathToModule(file);
console.log("adding " + file + " as " + normalPath + " to allTestFiles array");
allTestFiles.push(normalPath);
}
});
requirejs.config({
baseUrl: "/base/client/components/"
/*
* "path" is defined in require-shared.js and shared with
* require-main. Add paths for the testing files.
*/
,paths: {
"test": "../../test",
"bower": "../../bower_components",
"angular-mocks": "bower/angular-mocks/angular-mocks"
}
,shim: {
'angular-mocks': {
deps: [ 'ng-resource' ],
exports: 'angular.mock'
}
}
,deps: allTestFiles
,callback: window.__karma__.start
});
test/unit/testSpec.js
describe('a basic test of version', function() {
it('true should be true', function() {
expect(true).toBe(true);
});
});
The problem was that the TEST_REGEXP generated by karma init looked for either spec or test in the filename. This resulted in the require-test.js file getting pulled in as a test specification.
The solution is one of
rename require-test.js
change (spec|test) to just spec in the RE
change the RE to /^(?:(?!require-test\.js$).)*(spec|test)\.js$/i (see also, this answer)
This could also be the cause of your problem as it reports the same error under alternate circumstances (missing package.json): https://github.com/tkellen/js-matchdep/issues/11. However, if you are seeing this error message with this outcome, then you're running an older version of npm. Upgrading will give you a different error message (according to the thread).

Categories

Resources