Premise: my app works perfectly, but anyway I decided to imoplement units tests.
My test, that check if a service given object is defined or not fails.
here is my service code:
//app/components/lib/search.js
angular.module("search", ["lazyLoad", "httpInterceptor"])
.service("SearchObject", ['$rootScope', '$location', 'Globals', function ($rootScope, $location, Globals) {
'use strict';
var obj,
SearchObjectPrototype = {};
SearchObjectPrototype.clone = function (source) {
var prop;
for (prop in this) {
if (this.hasOwnProperty(prop)) {
this[prop] = source[prop] || null;
}
}
};
//Definizione SearchObject
obj = Object.create(SearchObjectPrototype, {
q : {value: null, writable: true, enumerable: true},
max_id : {value: null, writable: true, enumerable: true},
next_results : {value: null, writable: true, enumerable: true},
query_debug : {value: null, writable: true, enumerable: true}
});
Object.preventExtensions(obj);
this.getInstance = function () {
return obj;
};
}])
Here is my test code:
console.log(1);
describe('search module', function() {
console.log(2);
beforeEach(module('search'));
describe('SearchObject test', function() {
console.log(3);
var SearchObject;
beforeEach(inject(function(_SearchObject_){
console.log(4);
// The injector unwraps the underscores (_) from around the parameter names when matching
SearchObject = _SearchObject_;
}));
it('should evaluate the injected SearchObject', function (){
console.log(5);
expect(SearchObject).toBeDefined()
});
});
});
Here is my karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-10-20 using
// generator-karma 1.0.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: '../',
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.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-touch/angular-touch.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
'bower_components/Chart.js/Chart.js',
'bower_components/angular-chart.js/dist/angular-chart.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/components/lib/search.js",
// "test/mock/**/*.js",
"test/spec/search.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"
],
// Which plugins to enable
plugins: [
"karma-chrome-launcher",
"karma-phantomjs-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_'
});
};
Here my Karma output
Running "karma:unit" (karma) task
11 02 2016 11:55:43.447:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:8080/
11 02 2016 11:55:43.474:INFO [launcher]: Starting browser PhantomJS
11 02 2016 11:55:46.510:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on s
ocket /#OphIJTNigEfxY1NIAAAA with id 56068342
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 1
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 2
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 3
LOG: 5
PhantomJS 2.1.1 (Windows 8 0.0.0) test sul modulo search SearchObject test shoul
d evaluate the injected SearchObject FAILED
C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/angular.j
s:4459:53
forEach#C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/a
ngular.js:340:24
loadModules#C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angul
ar/angular.js:4419:12
createInjector#C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/an
gular/angular.js:4344:22
workFn#C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular-mo
cks/angular-mocks.js:2428:60
**Expected undefined to be defined.**
C:/Users/Rick/Sviluppo/socialsider-fe/test/spec/search.js:19:45
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.043 se
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.019 secs
/ 0.043 secs)
As you can see log(4), which is in the same block of SearchObject assignement, didn't get called. The object is undefined and the test fails.
Anyone can explain me why? It can be a dependency problem?
I have found that you need to inject your services/factories yourself:
beforeEach(function() {
module('search'));
inject(function(_SearchObject_) {
SearchObject = _SearchObject_;
});
});
That should make the service available to the tests. I just went back and spot checked some of my own tests and saw that this was the common piece all of my factory and service tests had.
Update:
After further review, there are some really odd things going on here and possibly multiple issues that need to be resolved. I don't have all of your dependency libraries and the angular module wouldn't load at all in the tests without mocking or removing lazyLoad and httpInterceptor. I'm going to assume that isn't your issue though and the module loads. After that once I mocked out Globals it loads just fine.
So in short, be sure you are properly providing lazyLoad, httpInterceptor, and Globals to the test, either with the actual code or through mocking, and the test passes. At least for me it does.
Related
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
})
}
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
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.
I have the following karma test for the angular-fullstack scaffold:
describe('Directive: categoryLookAhead', function () {
// load the directive's module and view
beforeEach(module('portfolioApp'));
beforeEach(module('app/article/Directives/categoryLookAhead/categoryLookAhead.html'));
var element, scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<category-look-ahead></category-look-ahead>');
element = $compile(element)(scope);
scope.$apply();
expect(element.text()).not.toBe(null);
}));
});
and this is my karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'client/bower_components/jquery/dist/jquery.js',
'client/bower_components/angular/angular.js',
'client/bower_components/angular-mocks/angular-mocks.js',
'client/bower_components/angular-resource/angular-resource.js',
'client/bower_components/angular-cookies/angular-cookies.js',
'client/bower_components/angular-sanitize/angular-sanitize.js',
'client/bower_components/angular-route/angular-route.js',
'client/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'client/bower_components/lodash/dist/lodash.compat.js',
'client/bower_components/angular-socket-io/socket.js',
'client/bower_components/angular-ui-router/release/angular-ui-router.js',
'client/bower_components/angular-markdown/angular.markdown.js',
'client/bower_components/angular-ui-router-title/angular-ui-router-title.js',
'client/app/app.js',
'client/app/app.coffee',
'client/app/**/*.js',
'client/app/**/*.coffee',
'client/components/**/*.js',
'client/components/**/*.coffee',
'client/app/**/*.jade',
'client/components/**/*.jade',
'client/app/**/*.html',
'client/components/**/*.html'
],
preprocessors: {
'**/*.jade': 'ng-jade2js',
'**/*.html': 'html2js',
'**/*.coffee': 'coffee',
},
ngHtml2JsPreprocessor: {
stripPrefix: 'client/'
},
ngJade2JsPreprocessor: {
stripPrefix: 'client/'
},
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
and this is the directive's controller:
angular.module('portfolioApp')
.directive('categoryLookAhead', function($interval, $filter) {
return {
templateUrl: 'app/article/Directives/categoryLookAhead/categoryLookAhead.html',
restrict: 'E',
scope: {
suggestedTags: '=',
selectedTags: '='
},
...
In my head, it should just compile from that template and start doing its thing but I get an error:
Error: Unexpected request: GET app/main/main.html
main.html does not include this directive at all, so I don't know why it's getting an unexpected request for this.
I've read in other StackOverflow posts that I can use whenGET(*).passThrough() to ignore these things, but I'd like to know why it's making a request to a module that has nothing to do with the directive.
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_'
});
};