Grunt Karma Hangs Forever - javascript

I have 2 configurations I want to test, wrapper and app. For technical reasons, these need to be separated configurations. When I run either, "grunt karma:app" or "grunt karma:wrapper" I get the following:
Running "karma:wrapper" (karma) task
INFO [karma]: Karma v0.12.32 server started at http://localhost:9876/
Which hangs indefinitely. Bellow is my grunt configuration:
karma: {
app: {
unit: {
configFile: 'test/karma.app.conf.js',
singleRun: true
}
},
wrapper: {
unit: {
configFile: 'test/karma.wrapper.conf.js',
singleRun: true
}
}
}
Bellow are both my karma configuration files:
App
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-04-14 using
// generator-karma 0.9.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// base path, that will be used to resolve files and exclude
basePath: '../dist',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine-jquery', 'jasmine'],
// list of files / patterns to load in the browser
files: [
// scripts
'app.min.js',
// test files
'../test/spec/*.app.spec.js'
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'Chrome_without_security'
],
customLaunchers: {
Chrome_without_security: {
base: 'Chrome',
flags: ['--disable-web-security', '--debug']
}
},
// Which plugins to enable
plugins: [
'karma-jasmine-jquery',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
proxies: {
'/': 'http://localhost:9000/'
}
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
Wrapper
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-04-14 using
// generator-karma 0.9.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../dist',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine-jquery', 'jasmine'],
// list of files / patterns to load in the browser
files: [
// scripts
'iWrapper.min.js',
// test files
'../test/spec/*.wrapper.spec.js'
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
customLaunchers: {
Chrome_without_security: {
base: 'Chrome',
flags: ['--disable-web-security', '--debug']
}
},
// Which plugins to enable
plugins: [
'karma-jasmine-jquery',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// }
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};

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

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__/'
})
};

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']
});
};

getting 'require is not defined' when testing in angularjs with karma

I am using angulajs with browersify to build an app. To test it, I'd like to use Karma.
I jave set up my conf file like this:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/app/*',
'src/app/*/*'
],
exclude: [
'src/app/*/*.jade'
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserify: {
debug: true
},
preprocessors: {'src/app/*/*.js': ['browserify']}
});
};
And my app.js file looks like this:
require('angular')
require('angular-mocks')
var uiRouter = require('angular-ui-router')
var serices = require('./services')
var directives = require('./directives')
var controllers = require('./controllers')
var routes = require('./routes')
angular.module('myApp', [uiRouter, 'ngMocks'])
// load Routes
.config(routes)
// Services
.service('someService', services.someService)
// Controllers
.controller('myCtrl', controllers.myCtrl)
// Directives
.directive('myDirective', directives.myDirective);
I am using karma-browserify but I still get the following error when running test:
'require is not defined'
How can I fix this?
You need to run browserify on your unit test files and include them in the files. I'm here including bundled.js, which is browserified app code.
This one is close to yours and it works.
(function() {
'use strict';
// Karma configuration
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-as-promised', 'chai', 'browserify'],
// list of files / patterns to load in the browser
files: [
// app-specific code. This should be generated by gulp browserify. Includes Angular
'webapp/bundled.js',
// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',
// test files
'unit/**/*.js'
],
// list of files to exclude
exclude: ['karma.conf.js', 'protractor-conf.js'],
// Browserify config
browserify: {
watch: true,
debug: true
},
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'unit/**/*.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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// - IE
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers: ['Chrome', 'IE', 'Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
})();

Categories

Resources