unit-testing on ionic service undefined - angularjs

happy holidays!, I'm facing an issue that I don't know why it's giving me:
//LoginCtrl:
angular.module('login.controller', [])
.controller('LoginCtrl', function($scope, $state, $translate, $ionicPopup, UserService, Auth) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
// Form data for the login modal
$scope.loginData = {};
// Perform the login action when the user submits the login form
$scope.doLogin = function() {
var onSuccess = function(response) {
if (response.data.user !== null) {
Auth.setUser(response.data.user);
Auth.setToken(response.data.user.token);
$state.go('app.main');
} else if (response.data.result == 101) {
$ionicPopup.alert({
title: $translate.instant('login_error'),
template: $translate.instant('login_not_verified')
});
}else {
$ionicPopup.alert({
title: $translate.instant('login_error'),
template: $translate.instant('login_bad_password_text')
});
}
};
var onError = function() {
$ionicPopup.alert({
title: $translate.instant('login_error'),
template: $translate.instant('login_error_text')
});
};
console.log('Doing login', $scope.loginData);
UserService.login($scope.loginData.username, $scope.loginData.password).then(onSuccess, onError);
};
$scope.doRegister = function() {
$state.go("register");
};
});
// Login Ctrl Test
describe('LoginCtrl', function() {
var controller,
deferredLogin,
userServiceMock,
stateMock,
scopeMock,
ionicPopupMock;
//Load the App module
beforeEach(module('starter'));
// Instantiate the Controller and Mocks
beforeEach(inject(function($controller, $q, $rootScope, $translate, Auth) {
deferredLogin = $q.defer();
scopeMock = $rootScope.$new();
// mock userServiceMock
userServiceMock = {
login: jasmine.createSpy('login spy')
.and.returnValue(deferredLogin.promise)
};
//mock $state
stateMock = jasmine.createSpyObj('$state spy', ['go']);
//mock $ionicPopup
ionicPopupMock = jasmine.createSpyObj('$ionicPopup spy', ['alert']);
//Instantiate LoginCtrl
controller = $controller('LoginCtrl', {
'$scope' : scopeMock,
'$state' : stateMock,
'$translate' : $translate,
'$ionicPopup' : ionicPopupMock,
'UserService' : userServiceMock,
'Auth' : Auth
});
}));
describe('#doLogin', function() {
// Call doLogin on the Controllers
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
controller.$scope.loginData.username = 'test';
controller.$scope.loginData.password = 'password';
controller.$scope.doLogin();
}));
it('should call login on userService', function() {
expect(userServiceMock.login).toHaveBeenCalledWith('test','password');
});
describe('when the login is executed,', function() {
it('if successful, should change state to app.main', function() {
//TODO: Mock the login response from userService
expect(stateMock.go).toHaveBeenCalledWith('app.main');
});
it('if unsuccessful, should show popup', function() {
//TODO: Mock the login response from userService
expect(ionicPopup.alert).toHaveBeenCalled();
});
});
});
});
The problem is that when I execute the test when it executes expect(userServiceMock.login).toHaveBeenCalledWith('test','password'); it gives me the following error:
TypeError: undefined is not an object (evaluating 'userServiceMock.login') in unit-tests/login.controller.tests.js (line 56)
I don't know userServiceMock gives me undefined.
Thank you all, if you need more code or something say me please.
This is my karma conf:
// Karma configuration
// Generated on Mon Dec 26 2016 10:38:06 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'],
// list of files / patterns to load in the browser
files: [
'../www/lib/ionic/js/ionic.bundle.js',
'../www/js/**/*.js',
'../www/lib/angular-mocks/angular-mocks.js',
'../www/lib/angular-translate/angular-translate.js',
'../www/lib/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'unit-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: ['PhantomJS'],
// 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
});
};

The problem was that I was not including translate libs on test.conf, and then that i was not taking the variables from the controller.

Related

inject a custom service in karma jasmine

I was trying out jasmine with karma. I have a custom service
ApiService which i need to inject in my spec file. But when am trying
to inject the ApiService i get Error: [$injector:unpr] Unknown
provider: ApiService <- ApiService
this is my controller
'use strict';
angular.module('assessmentApp')
.controller('NewUserController', NewUserController)
.run(["$rootScope", "$anchorScroll", function($rootScope, $anchorScroll) {
$rootScope.$on("$locationChangeSuccess", function() {
$anchorScroll();
});
}]);
NewUserController.$inject = ['$scope', '$rootScope', '$location', '$timeout', 'ApiService'];
function NewUserController($scope, $rootScope, $location, $timeout, ApiService) {
//console.log("innn NewUserController2 ::::")
var vm = this;
var boardsClassSubjectCombinations = [];
var studentId = $rootScope.globals.studentId;
var assessmentCampaignId = $scope.assessmentCampaignId = $rootScope.globals.assessmentCampaignId;
vm.currentQuestion = 1;
//sanity check if the user already has academics added
ApiService.getAll('students/' + studentId + '/latest-student-academic', true, ['students/{{id}}/academic'])
.then(function(res) {
if (res.data) {
//send this guy to home page
$location.url('/home');
}
});
function getStates() {
ApiService.getAll('states', true).then(function(response) {
$scope.states = response.data;
});
}
getStates();
}
this is my test file
describe('NewUserController Test', function() {
beforeEach(module('assessmentApp'));
// beforeEach(module('assets'));
//beforeEach(module('ApiService'))
var scope, location, timeout,apiService, q, authenticationService;
beforeEach(inject(function($location,$rootScope,$timeout, ApiService){
scope = $rootScope.$new();
location = $location;
timeout = $timeout;
q = _$q_;
console.log(ApiService)
//spyOn(ApiService, 'ApiService');
//spyOn(Point, 'method');
// console.log("ApiService :::"+ApiService)
//$controller = _$controller_('NewUserController', { $scope: $scope });
//console.log("NewUserController======="+$controller)
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
console.log("$location ::::"+location)
console.log("scope ::::"+scope)
console.log("timeout ::::"+timeout)
console.log("ApiService ::::"+ApiSrvce)
console.log("q ::::"+q)
//console.lopg("authenticationService :::"+authenticationService)
//console.log("$scope ::::::"+$scope)
expect(true).toEqual(true);
});
});
});
This 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: [
//'test-main.js',
'../bower_components/jquery/dist/jquery.js',
'../bower_components/angular/angular.js',
'../bower_components/bootstrap/dist/js/bootstrap.js',
'../bower_components/angular-route/angular-route.js',
'../bower_components/particles.js/particles.js',
'../bower_components/angular-cookies/angular-cookies.js',
'../bower_components/toastr/toastr.js',
'../bower_components/angular-sanitize/angular-sanitize.js',
'../bower_components/d3/d3.js',
'../bower_components/c3/c3.js',
'../bower_components/moment/moment.js',
'../bower_components/humanize-duration/humanize-duration.js',
'../bower_components/angular-timer/dist/angular-timer.js',
'../bower_components/underscore/underscore.js',
'../bower_components/scrollreveal/dist/scrollreveal.js',
'../bower_components/lodash/lodash.js',
'../bower_components/angular-youtube-mb/src/angular-youtube-embed.js',
'../bower_components/angular-mocks/angular-mocks.js',
//'../assets/**/*.js',
//'../assets/**/*.html',
//'../bower_components/angular/angular.js',
//'../bower_components/angular-mocks/angular-mocks.js',
'../app/scripts/app.js',
'../app/scripts/controllers/**/*.js',
'../app/scripts/directives/**/*.js',
'../app/scripts/services/**/*.js',
'../app/scripts/**/*.js',
'../../assets/src/assets/services/*.js',
'spec/**/*.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: ['PhantomJS'],
// 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
})
}
What i see is, when i try to inject any custom service it skips the beforeEach function and the logs i get in it function is
LOG: '$location ::::undefined'
LOG: 'scope ::::undefined'
LOG: 'timeout ::::undefined'
LOG: 'ApiService ::::undefined'
So I would suggest this kind of structure:
angular.mock.module(function($provide) {
apiService = jasmine.createSpy('apiService', ['getAll']);
$provide.value('apiService', apiService);
// Mock out other services here in the same fashion;
});
inject(function(_$controller_, _$rootScope_) {
$controller =
_$controller_('NewUserController', { $scope: _$rootScope_.$new() });
});
Then in your tests, you would refer to the apiService like this. Ideally you would make an it() statement for each bit you want to test, like say, the return value of getState(), but we'll do it all in one here:
it ('calls getState()', function () {
// Mock out what the apiService will do; you only care what comes back
// so you can see what $scope.states looks like in the end;
apiService.getAll.and.returnValue({ Promise.resolve({ foo: 1 }) });
// Spy on the controller's own getState method;
spyOn($controller, 'getState').and.callFake(() => true);
// Store the return value of the getState call;
expect($controller.getState).toHaveBeenCalled();
// Overall the calls count for getAll on the apiService should be two;
expect(apiService.getAll.calls.count()).toEqual(2);
// getState() will have been called, and should return the object;
expect($controller.states).toEqual({ foo: 1 });
});

Karma is not getting my $scope from controller

I'm trying to test a controller function however Karma cannot pick it up as expected. I have followed instruction from:https://docs.angularjs.org/guide/controller
Here is my code:
var app = angular.module('calApp', []);
app.controller('calCtrl', function($scope) {
$scope.sum = function(x, y) {
return x + y;
};
});
describe('calCtrl function', function() {
describe('calCtrl', function() {
var $scope;
beforeEach(module('calApp'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.new();
$controller('calCtrl', {$scope: $scope});
}));
it('should add 2 numbers correctly', function() {
expect($scope.sum(1, 2)).toBe(3);
});
it('should subtract 2 numbers correctly', function() {
expect($scope.subtract(5, 3)).toBe(2);
});
});
});
I expect the test to give 1 pass for $scope.sum() and 1 fail for $scope.substract(). Please help!
Error:
TypeError: undefined is not an object (evaluating '$scope.subtract') in tests/spec.js
Also:
Executed 2 of 2 (2 FAILED)
karma.conf.json:
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: [
'lib/angular.js',
'lib/angular.min.js',
'lib/angular-mocks.js',
'public_html/*.html',
'public_html/*.js',
'tests/*.js'
],
// list of files to exclude
exclude: [
"**/angular-scenario.js"
],
// 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: ['PhantomJS'],
// 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
})
}
UPDATE: I also have a FAILED for expect(true).toBe(true)
You don't have subtract defined.
Define subtract
app.controller('calCtrl', function($scope) {
$scope.subtract= function(x, y) {
return x - y;
};
$scope.sum = function(x, y) {
return x + y;
};
});
OR you can write the subtract in following way:-
it('should subtract 2 numbers correctly', function() {
expect($scope.subtract).toBeDefined();
expect($scope.subtract(5, 3)).toBe(2);
});
UPDATED based on errors:
Your beforeEach has problem
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
Then further in your tests you create:
it('should add 2 numbers correctly', function() {
var $scope = {};
var controller = $controller('calcCtrl', {$scope:$scope});
expect($scope.sum(1, 2)).toBe(3);
});
Follow ANgularJS Unit Testing Guite

$controller service throwing error while loading controller

I'm using Angular 1.5.8. Here is my code:
describe('My Controller', function() {
var MyController;
var $controller;
var $rootScope;
var $state;
beforeEach(angular.mock.module('ui.router'));
beforeEach(module('app.my.ctrl'));
beforeEach(inject(function(_$controller_, _$rootScope_, _$state_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
$state = _$state_;
MyController = $controller('MyController', { scope: $rootScope.$new() });
}));
describe('#init', function() {
it('should do something', function() {
console.log('logStatement', MyController);
MyController.init();
expect(true).toBe(true);
})
})
});
The test runner is able to locate all files, so this isnt a case of forgetting to load something. When I run this test, not only does the logStatement never appear, I get this error:
Argument 'MyController' is not a function, got undefined
This is my controller:
(function() {
'use strict';
angular
.module('app.my.ctrl')
.controller('MyController', MyController);
MyController.$inject = [
'$scope'
];
/* ngInject */
function MyController($scope) {
var vm = this;
vm.hello = 'world';
vm.init = function() {
return true;
}
}
})();
and this is my karma conf file:
// 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: ['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-ui-router/release/angular-ui-router.js',
'src/controllers/MyController.js',
'tests/unit/**/*.spec.js',
],
// list of files to exclude
exclude: [
'**/*.swp'
],
// 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: ['spec'],
// Spec Reporter Config
specReporter: {
// suppressErrorSummary: false,
// suppressFailed: false,
// suppressPassed: false,
suppressSkipped: true
// showSpecTiming: false
},
// 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: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
};
What does this mean?? I can't find anything in the documentation that would explain this.
UPDATE:
I've read this answer and the answer has not worked.
Trying change the service injected in the controller from scope to $scope
beforeEach(inject(function(_$controller_, _$rootScope_, _$state_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
$state = _$state_;
MyController = $controller('MyController', { $scope: $rootScope.$new()});
}));
Did you try to make your pb as simple as possible? Inside the application can you successfully make this call? $controller('MyController', { $scope: $rootScope.$new()}); . If this works (it actually should), the problem definitively comes from your test/jasmin/karma/gulp/grunt configuration and you shouldn't dig into angular direction anymore. Can you give us a look at how you define the app.my.ctrl module in your application? Maybe this module depends on more modules than only ui.router that you mock in your test. If it's the case, the module can't be loaded, and any controller inside can't be created either.
describe('My Controller', function() {
var MyController;
var scope;
beforeEach(angular.mock.module('ui.router'));
beforeEach(module('app.my.ctrl'));
beforeEach(inject(function($rootScope) {
scope = $rootScope.$new();
}));
describe('#init', function() {
it('should do something', function($componentController) {
var MyController = $componentController('MyController', {
$scope : scope
});
MyController.init();
expect(true).toBe(true);
})
})
});

Angular unit test: TypeError: $controller is not a function

am setting up unit test for Angular application build with webpack how ever am getting this error when am running my first simple test.
TypeError: $controller is not a function
The controller code like this :
(function() {
'use strict';
angular
.module('dpServerV2WebappRev2App.controllers')
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.x = 'x';
}
})();
Where the test look like this:
describe('MainCtrl', function () {
beforeEach(module('dpServerV2WebappRev2App.controllers'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.brand', function () {
it('should match the brand portal name', function () {
var $scope = {};
var controller = $controller('MainCtrl', { $scope: $scope });
expect($scope.x).toEqual('x');
});
});
});
Just to clear things more I have comment out the test code where I test the $scope.x and replace it with this:
expect(1).toEqual(1);
Therefor I got this error
at Error (native)
at node_modules/angular/angular.min.js:6:412
at node_modules/angular/angular.min.js:40:134
at r (node_modules/angular/angular.min.js:7:355)
at g (node_modules/angular/angular.min.js:39:222)
at Object.db [as injector] (node_modules/angular/angular.min.js:43:246)
at Object.workFn (node_modules/angular-mocks/angular-mocks.js:3067:5
I have commented out my module injection in the test and now the test is passing however when including the module is still getting the above error:
The new test code that cause no problems:
describe('MainCtrl', function () {
describe('$scope.brand', function () {
it('should match the brand portal name', function () {
expect(1).toEqual(1);
});
});
Since it seems config problem to me I'll add my Karma config file:
var webpackConfig = require('./webpack.config.js');
webpackConfig.entry = {};
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/angular/angular.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'assets/app.bundle.js',
'app/*.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: {
'./assets/app.bundle.js': ['webpack'],
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
// 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,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
Working with the angular mocks, sometimes is very strange when we deal with services. Try this
describe('MainCtrl', function () {
beforeEach(module('dpServerV2WebappRev2App.controllers'));
var controllerInjector, myController;
beforeEach(inject(function($controller){
controllerInjector = $controller;
}));
describe('$scope.brand', function () {
it('should match the brand portal name', function () {
var $scope = {};
myController = controllerInjector('MainCtrl', { $scope: $scope });
expect($scope.x).toEqual('x');
});
});
});
Demo : http://codepen.io/gpincheiraa/pen/jAgNpW

Unit testing a Angular service call using karma/jasmine

I am getting following service undefined error when i try to unit test a service call return in my app . I spend several hours on this , but i couldn't really isolate where the issue comes from . Appreciate if anyone could help me out with this .
Firefox 38.0.0 (Windows 8.1) companyService should return a promise for getCompany function FAILED
minErr/<#C:/Users/user1m/Documents/mycompany/WebApiRole/bower_components/angular/angular.js:63:12
loadModules/<#C:/Users/user1m/Documents/mycompany/WebApiRole/bower_components/angular/angular.js:4138:15
forEach#C:/Users/user1m/Documents/mycompany/WebApiRole/bower_components/angular/angular.js:323:11
loadModules#C:/Users/user1m/Documents/mycompany/WebApiRole/bower_components/angular/angular.js:4099:5
createInjector#C:/Users/user1m/Documents/mycompany/WebApiRole/bower_components/angular/angular.js:4025:11
workFn#C:/Users/user1m/Documents/mycompany/WebApiRole/node_modules/angular-mocks/angular-mocks.js:2409:44
TypeError: companyService is undefined in C:/Users/user1m/Documents/mycompany/WebApiRole/test/company/Compa
nyServiceSpec.js (line 15)
#C:/Users/user1m/Documents/mycompany/WebApiRole/test/company/CompanyServiceSpec.js:15:16
Firefox 38.0.0 (Windows 8.1): Executed 1 of 1 (1 FAILED) ERROR (0.031 secs / 0.014 secs)
My karma.conf.js file
// 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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/requirejs/require.js',
'bower_components/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'bower_components/ng-file-upload/**/*.js',
'bower_components/angular-ui-router/release/**/*.js',
'bower_components/angular-bootstrap/**/*.js',
'bower_components/angular-translate/**/*.js',
'bower_components/angular-translate-loader-static-files/**/*.js',
'bower_components/angular-pnotify/src/**/*.js',
'bower_components/angular-local-storage/**/*.js',
'bower_components/angular-loading-bar/build/**/*.js',
'app/app.js',
'app/**/*.js',
'test/**/*Spec.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
hostname: 'localhost',
port: 44555,
// 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
});
};
CompanyServiceSpec.js file
'use strict';
describe('companyService', function() {
var $httpBackend, companyService;
beforeEach(angular.mock.module('mycompany'));
beforeEach(angular.mock.inject(function(_$httpBackend_, _companyService_) {
$httpBackend = _$httpBackend_;
companyService = _companyService_;
}));
it('should return a promise for getCompany function', function() {
expect(typeof companyService.getCompany('foobar').then).toBe('function');
});
});
CompanyService.js file
angular.module('mycompany').factory('companyService',
function($http, mycompanyApiProvider, $upload) {
'use strict';
var _company = null;
function getCompany(companyId) {
return $http.get(mycompanyApiProvider.url('companies/' + companyId));
}
});
app.js file
angular.module('mycompany', [
'ui.router',
'ui.router.util',
'angularFileUpload',
'pascalprecht.translate',
'jlareau.pnotify',
'LocalStorageModule',
'angular-loading-bar',
'ui.bootstrap',
'angularMoment',
'frapontillo.bootstrap-switch'
]);
angular.module('mycompany').run(function (mycompanyApiProvider, $state, userService, localStorageService,
$translate, $rootScope, $window, $timeout) {
'use strict';
mycompanyApiProvider.setEndpoint('/api/');
mycompanyApiProvider.loginUrl = '/home/login';
});
mycompanyApiProvider.js file
'use strict';
angular.module('mycompany')
.provider('mycompanyApiProvider', function($httpProvider, $provide) {
$provide.factory('jsonHeaderInterceptor', function() {
return {
'request': function(config) {
// config.headers['Content-Type'] = 'application/json';
return config;
}
};
});
});
Folder structure
Folder structure :
|WebApiRole/Karma.Conf.js
|WebApiRole/app/app.js
|WebApiRole/app/company/CompanyService.js
|WebApiRole/app/common/services/mycompanyApiProvider.js
|WebApiRole/test/company/CompanyServiceSpec.js
The companyService factory doesn't return anything, so it's treated as having returned undefined. The test seems to be testing that it returns an object with a getCompany function, so you can change it so it does:
angular.module('mycompany').factory('companyService', function($http, mycompanyApiProvider, $upload) {
'use strict';
var _company = null;
function getCompany(companyId) {
return $http.get(mycompanyApiProvider.url('companies/' + companyId));
}
return {
getCompany: getCompany
};
});

Resources