Hans Petter Naumann Hans Petter Naumann - 1 year ago 243
Javascript Question

Testing service with angular-mocks/jasmine - TypeError: undefined is not an object

Im trying to test a simple service in my angular app, using jasmine/karma/phantomJS.

jasmine version: 2.4.1
angular/angular-mocks: 1.5.7
phantomJS: 2.1.1

QueryParameters.service.tests.js : (QueryParameters.service.js is part of the app.service module, and is actually a factory, not a service)

describe('myApp.QueryParametersService', function() {

var QueryParametersService;

beforeEach(inject(function ($injector) {
QueryParametersService = $injector.get('QueryParametersService');

var testObject = {
name : 'Hans',
age : '27'

it('Should output correct querystrings', function() {



(function() {
'use strict';

.factory('QueryParametersService', QueryParametersService);

QueryParametersService.$inject = [];

function QueryParametersService() {

var service = {
toQueryParams : toQueryParams

return service;

function toQueryParams(queryObject) {
<removed code here>

In Gruntfile.js:

karma: {
unit: {
options: {
frameworks: ['jasmine'],
singleRun: true,
browsers: ['PhantomJS'],
files: [
'<%= yeoman.client %>/bower_components/angular/angular.js',
'<%= yeoman.client %>/bower_components/angular-mocks/angular-mocks.js',
'<%= yeoman.client %>/app/app.js',
'<%= yeoman.client %>/app/filters/filter.module.js',
'<%= yeoman.client %>/app/directives/directive.module.js',
'<%= yeoman.client %>/app/services/service.module.js',
'<%= yeoman.client %>/app/services/tests/*.js'

my main module (in app.js) is declared like this:

angular.module('myApp', [

The error im getting when running the tests:

PhantomJS 2.1.1 (Mac OS X 0.0.0) myApp.QueryParametersService Should output correct querystrings FAILED
TypeError: undefined is not an object (evaluating 'QueryParametersService.toQueryParams') in /<filepath>/client/app/services/tests/query-parameters.service.tests.js (line 65)
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.002 secs / 0.009 secs)

Where am I going wrong here?

Answer Source

As @jchen86 pointed out, QueryParametersService.js wasnt included in config (I thought it woul be included when i included the whole service module). Solved by changing the gruntfile to include all js files in the service folder:

'<%= yeoman.client %>/app/services/*.js'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download