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
Related
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 });
});
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);
})
})
});
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
I am on mean stack and i don't understand which files am i missing or where am i going wrong because my scopes says Expected undefined to be defined. Tell me what i am missing.
test.js
describe('Testing Ecdreport Controllers', function(){
var $scope, createController;
beforeEach(module('mean.ecdreport', function($provide, $controllerProvider){
$controllerProvider.register('Ecdreportcontroller', function($scope){
//console.dir($scope)
})
}));
it('Should inject Dependencies', inject(function(){
expect('mean.ecdreport').toBeDefined();
}))
beforeEach(inject(function(_$rootScope_,_$controller_){
$scope = _$rootScope_.$new();
createController = function(){
return _$controller_('Ecdreportcontroller',
{ $scope : $scope
});
}
console.dir(_$controller_);
}));
it('Should be registered', function(){
var controller = new createController();
expect(controller).toBeDefined()
});
it('Testing Scope', function(){
//var controller = new createController();
expect($scope.package.name).toEqual('ecdreport');
})
});
controllers.js
var app = angular.module('mean.ecdreport',[])
.controller('EcdreportController', ['$scope', '$http', 'Global', 'Ecdreport', function($scope, $http, Global, Ecdreport) {
$scope.global = Global;
$scope.query = "";
$scope.package = {
name: 'ecdreport'
};
$scope.startDate = null;
$scope.endDate = null;
$scope.currentPage = 1;
$scope.child= [];
$scope.maxSize = 5;
$scope.items = [];
$scope.itemsPerPage = 10;
$scope.totalItems = null;
$scope.direction = 1;
$scope.directionOld = 1;
$scope.sortAttributes = 0;
$scope.sortAttributesOld = 0;
$scope.datamodel = null;
$scope.getDataModel = function() {
$http({url:'/api/v1/getdatamodel', method:"GET"})
.success(function(data) {
console.log('Datamodel successful');
$scope.datamodel = data[0];
console.log('datamodel', data);
})
.error(function(error) {
$scope.datamodel =[];
});
}
// console.log("Trying to get datamodel");
$scope.getDataModel();
}]);
karma.conf.js
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-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'packages/custom/ecdreport/public/controllers/ecdreport.js',
// 'packages/custom/ecdreport/public/routes/ecdreport.js',
// 'packages/custom/ecdreport/public/services/ecdreport.js',
//'packages/custom/ecdreport/public/views/index.html',
'packages/custom/ecdreport/test/Spec/controllers/ecdreport.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,
plugins: [
'karma-jasmine',
'karma-webpack',
'karma-ng-html2js-preprocessor',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-requirejs',
'karma-coverage',
'karma-junit-reporter'
],
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
};
I found out that mean.io has a built in karma.confg.js that does not need to be changed you just add a test file to your public folder and start testing.
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
};
});