error with mocha karma test runner - javascript

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.

Related

karma angular templateUrl not found

I've some problems when testing angular directives with karma, the problem is that when comes from templateUrl never translate it.
here is my karma.conf.js
'use strict';
var wiredep = require('wiredep');
var bowerFiles = wiredep().js;
var appFiles = [
'src/modules/**/*-module.js',
'src/modules/**/**/*.js',
{ pattern: 'src/modules/**/*.mol', watched: true, served: true, included: false },
'src/modules/**/**/templates/*.html',
{
pattern: '../src/assets/images/*.*',
watched: false,
included: false,
served: true
},
'src/modules/**/**/templates/*.html'
];
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',
'chai',
'sinon-chai'
],
junitReporter: {
outputFile: '../reports/test-results/test-results.xml'
},
coverageReporter: {
dir: 'reports/test-coverage/',
subdir: function (browser) {
// normalization process to keep a consistent browser name across different OS
return browser.toLowerCase().split(/[ /-]/)[0];
},
check: {
global: {
statements: 10,
branches: 1,
functions: 10,
lines: 10
},
each: {
statements: 0,
branches: 0,
functions: 0,
lines: 0
}
},
reporters: [
{ type: 'html', file: 'coverage.html' },
{ type: 'cobertura', file: 'coverage.xml' },
{ type: 'json' },
{ type: 'text-summary' }
]
},
reporters: ['junit', 'dots', 'coverage'],
// list of files / patterns to load in the browser
files: [].concat(bowerFiles, appFiles),
// 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: {
'src/modules/**/**/!(*.test).js': 'coverage',
'src/modules/**/**/templates/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'templates'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
// 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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};
And the test ...
'use strict';
describe('dra-header-directive', function () {
var compile;
var rootScope;
var templateCache;
beforeEach(module('dd'));
beforeEach(module('templates'));
beforeEach(inject(function ($compile, $rootScope, $templateCache) {
compile = $compile;
rootScope = $rootScope;
templateCache = $templateCache;
}));
it('Replace the element with the appropiate element', function () {
var scope = rootScope.$new();
var el = angular.element('<testing></testing><dra-header></dra-header><input-bar></input-bar>');
var element = compile(el)(scope);
scope.$digest();
console.log(element);
});
});
The first tag is translated due to is not defined as templateUrl, but the others don't.
if I get the templates with $templateCache I can read the content, so I asume ng-html2js is doing it's job. any ideas?
Thanks for helping!
Its solved, I changed the before each module to avoid importing unnecesary module dependencies, looks like there was something that was modifying my rootScope, I just loaded the module that has the directive, and now works fine
'use strict';
describe('dra-header-directive', function () {
var compile;
var scope;
var templateCache;
beforeEach(module('dra.components.DRAHeaderModule'));
beforeEach(function () {
module('templates');
});
beforeEach(inject(function ($compile, $rootScope, $templateCache) {
compile = $compile;
templateCache = $templateCache;
scope = $rootScope.$new();
}));
it('Replace the element with the appropiate element', function () {
var el = angular.element('<dra-header></dra-header>');
compile(el)(scope);
scope.$digest();
expect(el.find('div')[0]).to.not.be.undefined();
});
});

Unit Testing Browserify Project with Karma + Jasmine

I am trying to setup unit testing for a JavaScript plugin that is based on AngularJS. The plugin is bundled with Browserify via Gulp. It depends on external libraries that are injected with wiredep and gulp-inject from the bower_components folder. This is all working beautifully in the generated bundle, but if I try to run a Karma unit test via gulp, I get the following error:
Uncaught TypeError: angular.module is not a function at /tmp/94dbea5947f4758ab1ee6935e2f4b3f1.browserify:365 <- app/js/services/index.js:9:0
In this file, angular is loaded with var angular = require('angular');, and a console.log(angular) gives an empty object.
My karma.conf.js:
'use strict';
const istanbul = require('browserify-istanbul');
const isparta = require('isparta');
const mainBowerFiles = require('main-bower-files');
const karmaBaseConfig = {
basePath: '../',
frameworks: ['jasmine', 'browserify'],
preprocessors: {
'app/js/**/*.js': ['browserify', 'coverage'],
'**/*.html': ['ng-html2js']
},
browserify: {
debug: true,
extensions: ['.js'],
transform: [
[["babelify", {"ignore": "/\/bower_components\//"}]],
'browserify-ngannotate',
'bulkify',
'debowerify',
'brfs',
istanbul({
instrumenter: isparta,
ignore: ['**/bower_components/**', '**/node_modules/**', '**/test/**']
})
]
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/',
moduleName: 'templates'
},
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-browserify',
'karma-ng-html2js-preprocessor',
'karma-chrome-launcher'
],
files: mainBowerFiles({
filter: '**/*.js',
paths: {
bowerDirectory: 'bower_components',
bowerrc: '.bowerrc',
bowerJson: 'bower.json'
}
}).concat([
// app-specific code
'app/js/main.js',
// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',
// test files
'test/unit/**/*.js'
]),
exclude: [],
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
};
const customLaunchers = {
chrome: {
base: 'SauceLabs',
browserName: 'chrome'
}
};
const ciAdditions = {
sauceLabs: {
testName: 'Karma Unit Tests',
startConnect: false,
build: process.env.TRAVIS_BUILD_NUMBER,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
browsers: Object.keys(customLaunchers),
customLaunchers: customLaunchers,
reporters: ['progress', 'coverage', 'saucelabs']
};
module.exports = function (config) {
const isCI = process.env.CI;
config.set(isCI ? Object.assign(karmaBaseConfig, ciAdditions) : karmaBaseConfig);
};
All main application files are located under app/, bower files in bower_components/, node modules in node_modules/ and test specs in test/unit/.
It is based on this boilerplate: https://github.com/jakemmarsh/angularjs-gulp-browserify-boilerplate.
The error occurs just after Karma has launched Chrome, but before any unit test are executed (I checked with console.log in the unit test).
Any help would be greatly appreciated.
Finally solved it.
unit.js (gulp unit task):
'use strict';
import config from '../config';
import path from 'path';
import gulp from 'gulp';
import {Server} from 'karma';
gulp.task('unit', ['copy-bower-components',
'styles',
'images',
'fonts',
'api',
'views',
'browserify',
'inject'
], function (done) {
new Server({
configFile: path.resolve(__dirname, '../..', config.test.karma),
singleRun: true
}, function (exitCode) {
console.log('Karma has exited with ' + exitCode);
done();
}).start();
});
The key here was to run browserify before the unit tests are started. karma.conf.js:
// Karma configuration
// Generated on Sat Jan 23 2016 16:43:48 GMT+0100 (CET)
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', 'browserify'],
// list of files / patterns to load in the browser
files: [
"bower_components/tether/dist/js/tether.js",
"bower_components/jquery/jquery.js",
"bower_components/bootstrap/dist/js/bootstrap.js",
"bower_components/jquery-ui/jquery-ui.js",
"bower_components/rangy/rangy-core.js",
"bower_components/rangy/rangy-classapplier.js",
"bower_components/rangy/rangy-highlighter.js",
"bower_components/rangy/rangy-selectionsaverestore.js",
"bower_components/rangy/rangy-serializer.js",
"bower_components/rangy/rangy-textrange.js",
"bower_components/angular/angular.js",
"bower_components/textAngular/dist/textAngular.js",
"bower_components/textAngular/dist/textAngular-sanitize.js",
"bower_components/textAngular/dist/textAngularSetup.js",
"bower_components/KaTeX/dist/katex.min.js",
"bower_components/angular-bootstrap/ui-bootstrap-tpls.js",
"bower_components/angular-translate/angular-translate.js",
"bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js",
"bower_components/angular-cookies/angular-cookies.js",
"bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js",
"bower_components/angular-translate-storage-local/angular-translate-storage-local.js",
"bower_components/angular-translate-handler-log/angular-translate-handler-log.js",
"bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js",
"bower_components/angular-tour/dist/angular-tour-tpls.min.js",
"bower_components/ng-sortable/dist/ng-sortable.js",
"bower_components/moment/moment.js",
"bower_components/angular-moment/angular-moment.js",
"bower_components/KaTeX/dist/contrib/auto-render.min.js",
'dist/js/main.js',
'node_modules/angular-mocks/angular-mocks.js',
'test/unit/**/*.spec.js'
],
browserify: {
debug: true,
transform: [
'babelify',
'brfs',
'bulkify'
]
},
// list of files to exclude
exclude: ['karma.conf.js'],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/unit/**/*.spec.js': ['browserify']
},
// 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: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
urlRoot: '/__karma__/'
})
};

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.

sinon is undefined in testing plugin (parse-mock)

I am attempting to use Karma to run a testing framework over AngularJS. Our application uses Parse.com's NoSQL database, and we'd like to test our code without calling it, so I'm trying to use parse-mock to do it.
However, I'm pretty sure I'm setting something up wrong, because I've managed to get everything to the point where the only issue is that "sinon" is undefined in the plugin parse-mock.
Here is the karma.conf.js file:
// Karma configuration
// Generated on Fri Nov 13 2015 13:23:29 GMT-0600 (CST)
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', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test-main.js',
//{pattern: 'app/view*/**/*.js', included: false},
{pattern: 'app/js/parse-1.5.0.min.js', included: true},
{pattern: 'node_modules/underscore/underscore-min.js', included: true},
{pattern: 'node_modules/parse-mock/dist/parse-mock.latest.js', included: true},
{pattern: 'node_modules/parse-mock/test/exmaples/login.js', included: true}
],
// 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: {
},
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-sinon',
'karma-requirejs',
'karma-coffee-preprocessor'
],
// 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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
Here is the test-main.js file (requirejs configuration):
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
'sinon': 'node_modules/sinon/lib/sinon.js',
//'parse': 'app/js/parse-1.5.0.min.js'
},
use: {
'sinon': {
attach: 'sinon'
}
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
And finally, the relevant line from the parse-mock plugin:
sinon = (typeof window !== "undefined" ? window.sinon : typeof global !== "undefined" ? global.sinon : null)
I checked, both window.sinon and global.sinon are undefined, and I have no idea why.

Jasmine Tests give error "Uncaught ReferenceError: require is not defined"

I am trying to run Jasmine tests with Karma on my React site. My tests were working before, and I'm not sure what has changed, but now I get the error:
Uncaught ReferenceError: require is not defined
for Chrome and PhantomJS and Firefox give me similar errors. Please let me know if more info would be helpful. I have found a lot of similar questions on the web, but nothing that fixes the problem.
You can see the test file below and the full project is on my github repo.
Thanks in advance!
My test file looks like this:
var React = require('react/addons');
var Story = require('../../app/js/components/story.jsx');
var TestUtils = React.addons.TestUtils;
var testUtilsAdditions = require('react-testutils-additions');
describe('Story component', function () {
var component;
beforeEach(function () {
var element = React.createElement(Story);
element.props.data = {
storyTitle: 'front end test title',
author : 'front end author',
storyText : 'front end story text'
};
component = TestUtils.renderIntoDocument(element);
});
it('should display a story', function () {
expect(component.props.data).toBeDefined();
expect(component.props.data.storyTitle).toBeDefined();
expect(component.props.data.storyTitle).toBe('front end test title');
expect(component.props.data.author).toBe('front end author');
expect(component.props.data.storyText).toBe('front end story text');
});
});
My karma.conf.js file looks like this:
// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)
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: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'test/karma_tests/*test.js'
],
//plugins to start browsers
plugins : [
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-ie-launcher',
'karma-jasmine',
'karma-chai',
'karma-webpack'
],
// 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/karma_tests/*test.js': ['webpack'],
// 'test/**/*_test.js': ['webpack']
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
module: {
loaders: [{
test: /\.jsx$/,
loader:'jsx-loader'
}]
}
},
// 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: ['Chrome', 'Firefox', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
This is the error I get after making the changes #guilhebl recommended:
Firefox 40.0.0 (Ubuntu 0.0.0) ERROR
Error: Module name "react/addons" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
at /home/michael/repository/short-stories/node_modules/requirejs/require.js:165
Here is the karma.conf.js after I made the changes:
// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)
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: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'./node_modules/requirejs/require.js',
'./node_modules/karma-requirejs/lib/adapter.js',
'./test/karma_tests/*test.js'
],
//plugins to start browsers
plugins : [
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-ie-launcher',
'karma-jasmine',
'karma-chai',
'karma-webpack',
'karma-requirejs',
'karma-script-launcher'
],
// 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/karma_tests/*test.js': ['webpack'],
// 'test/**/*_test.js': ['webpack']
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
module: {
loaders: [{
test: /\.jsx$/,
loader:'jsx-loader'
}]
}
},
// 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: ['Chrome', 'Firefox', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
You should have require configured in your karma.conf file such as example:
module.exports = function(config){
config.set({
frameworks: ['jasmine'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-script-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-requirejs'
],
files : [
'node_modules/requirejs/require.js',
'node_modules/karma-requirejs/lib/adapter.js',
'app/js/test-main.js',
{pattern: 'app/lib/**/*.js', included: false},
{pattern: 'app/js/**/*.js', included: false},
{pattern: 'app/js/views/**/*Test.js', included: false}
],
browsers: ['PhantomJS']
});
};

Categories

Resources