Karma Jasmine Angular not defined - javascript

I am trying to learn how to use angular and karma to test angularjs and nodejs. I have used Noesavy's youtube videos to learn how to set up karma and jasmine. His examples work fine but when I try to use jasmine and karma with my own code I get angular undefined. My code is posted below:
passwordScript.js
angular.module('myApp', []).controller('S',
['$scope',
function($scope){
$scope.checkPass = function(insert_password, confirm_password){
if(insert_password == confirm_password){
$scope.passBoole = true;
} else {
$scope.passBoole = false;
}
};
}]);
checkPassSpec
describe("Password Controller", function(){
var $rootScope,
$scope,
controller;
beforeEach(function(){
module('myApp');
inject(function($injector){
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
controller = $injector.get('$controller')("S", {$scope: $scope});
});
});
describe('Password check', function(){
it('should set $scope.passBoole top false', function(){
checkPass("bob", "tom");
expect($scope.passBoole).toEqual(false);
})
it('should set scope.passBoole to true', function(){
checkPass("bob", "bob");
expect($scope.passBoole).toEqual(true);
});
});
});
karma.conf.js
// Karma configuration
// Generated on Thu Dec 11 2014 17:07:06 GMT+0000 (GMT)
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/angular/angular.js',
'./bower_components/angular-mocks/angular-mocks.js',
'./bower_components/angular-resource/angular-resource.js',
'app/**/*.js',
'test/**/*.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I really have no idea why this is happening and any help would be greatly appreciated.

files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'app/**/*.js',
'spec/**/*.js'
],
I know this is a late answer, but I had the same problem and removing the './' solved it for me

Please replace content of files:[] block inside karma.config.js with following
files: [
'/bower_components/angular/angular.js',
'/bower_components/angular-mocks/angular-mocks.js',
'/bower_components/angular-resource/angular-resource.js',
'app/**/*.js',
'test/**/*.js'
],

Related

TypeError: $httpBackend is undefined

I am developing an angular application. I have the application running with few controllers and services. Now I wanted to start unit testing the services and controllers. But don't know what I am doing wrong, I am not able to run a test properly for a even a single service. When I try to run the test using karma using:
karma start karma.conf.js
I get following error:
Firefox 38.0.0 (Windows 7 0.0.0) service: MyCategoryService should send a request to MyCategoryService FAILED
minErr/<#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:68:12
loadModules/<#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4458:15
forEach#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:340:11
loadModules#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4419:5
createInjector#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/bower_components/angular/angular.js:4344:11
workFn#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/libs/angular-mocks.js:2797:44
angular.mock.inject#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/libs/angular-mocks.js:2777:30
#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryService.test.js:18:9
TypeError: $httpBackend is undefined in c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryServi
ce.test.js (line 33)
#c:/Users/bgurung2/workspace/admintoolui/src/main/webapp/js/tests/services/preferenceCategoryService.test.js:33:9
Firefox 38.0.0 (Windows 7 0.0.0): Executed 13 of 13 (1 FAILED) (0.016 secs / 0.039 secs)
I am not sure where did I go wrong. I tried to follow this stackoverflow question but was out of clue.
Any help or suggestion would be great!!
Here is my app:
'use strict';
/* App Module */
var app = angular.module('myApp', [
'ngRoute', // uri routing
'controllers', // controllers
'services', // services
'ngMock'
]);
// module controllers
var appCtrl = angular.module('controllers', []);
// module services
var appServices = angular.module('services', [ 'ngResource' ]);
Here is my service:
'use strict';
appServices.factory('MyCategoryService', ['$resource', 'REST_RESOURCE',
function ($resource, REST_RESOURCE) {
return $resource(REST_RESOURCE.PREFERENCE, {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
}]);
Here is my Service Spec:
describe('service: MyCategoryService', function () {
var $httpBackend;
var $rootScope;
var MyCategoryService;
var REST_RESOURCE;
beforeEach(function () {
angular.mock.module('myApp');
angular.mock.inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
$rootScope = $injector.get('$rootScope');
MyCategoryService= $injector.get('MyCategoryService');
REST_RESOURCE = $injector.get('REST_RESOURCE');
});
});
it('should send a request to MyCategoryService', function () {
//TODO
var mockdata = {
items: {
}
};
$httpBackend.expect('GET', REST_RESOURCE.PREFERENCE).respond(200, mockdata);
MyCategoryService.query(function (response) {
$rootScope.data = response.items;
});
$httpBackend.flush();
expect($rootScope.data).toEqual(mockdata);
});
});
Here is my karma.conf.js file:
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: [
//dependencies
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-cookies/angular-cookies.js',
'js/app.js',
'js/libs/*.js',
'js/directives/*.js',
'js/routes.js',
'js/resource_uri.js',
'js/services/*.js',
'js/controllers/*.js',
//test files
'js/tests/*.test.js',
'js/tests/*/*.test.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: ['Firefox'],
// 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
});
};
I finally got my test running after going through some changes in some files. I don't know what the exact reason was, but I got it working with the following changes. Here's my changes below:
I removed ngMocks dependency. After changes, my app.js file looks like following.
'use strict';
/* App Module */
var app = angular.module('admintool', [ 'ngRoute', // uri routing
'controllers', // controllers
'services', // services
'angularUtils.directives.dirPagination', // pagination service
'ui.bootstrap', // angular ui bootstrap
'ui', // ui sortable
'uiSwitch', // on of switch service
'ngMessages', // for form validation
'xeditable', // for table edit
'ngCookies'
// messages
]);
// module controllers
var appCtrl = angular.module('controllers', []);
// module services
var appServices = angular.module('services', [ 'ngResource' ]);
service.js looks like:
'use strict';
//appServices.factory('PreferenceCategory', ['$resource', 'REST_RESOURCE',
angular.module('services').factory('PreferenceCategory', ['$resource', 'REST_RESOURCE',
function ($resource, REST_RESOURCE) {
return $resource(REST_RESOURCE.PREFERENCE_CATEGORY, {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
}]);
serviceSpec.js looks like:
describe('Preference Category Service',
function() {
beforeEach(angular.mock.module("admintool"));
var httpBackend, pc;
beforeEach(inject(function($httpBackend, PreferenceCategory) {
httpBackend = $httpBackend;
pc = PreferenceCategory;
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it(
'Check GET Request',
function() {
httpBackend
.expectGET(
'http://jboss-pmadmin-tool-dev.ose-core.optum.com/pmadmin-tool/v1/preference_categories')
.respond({
username : 'test'
});
// call the function on our service instance
var response = pc.query();
httpBackend.flush();
expect(response.username).toEqual('test');
});
});
karma.conf.js file, I removed 'js/libs/*' and added individual files that are used in the app.
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files,
// exclude)
basePath : '../admintoolui/src/main/webapp/',
// 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/angular/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'js/libs/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'js/libs/pagination.js',
'js/libs/angular-ui.js',
'js/libs/angular-ui-switch.min.js',
'js/libs/angular-messages.js',
'js/libs/xeditable.min.js',
'bower_components/angular-cookies/angular-cookies.js',
'js/app.js',
'js/resource_uri.js',
'js/services/*.js',
'js/controllers/*.js',
'js/tests/**/*.test.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 : [ 'Firefox' ],
// 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
})
}

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

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