question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unit Test using Karma for the controller with Service

See original GitHub issue

Thank you for the great material. But I have a question for the unit test.

I have created one angularjs service and tried to inject in my teams.spec.js for unit test. But I get the error like this. Error: [$injector:unpr] unknown provider : EnvServiceProvider <- EnvService …

Here is the source code.

import TeamsModule from './teams'
import TeamsController from './teams.controller';
import TeamsComponent from './teams.component';
import TeamsTemplate from './teams.html';
import Services from '../../services/services.js'

import 'ngstorage';
import env from '../../services/env.js'

describe('Teams', () => {
  let $rootScope, makeController, $localStorage, EnvService, $http;


  beforeEach(window.module(TeamsModule.name));
  beforeEach(window.module('ngStorage'));
  beforeEach(window.module(Services.name));

  // come out the error when injecting
  beforeEach(inject((_$rootScope_, _$http_, _$localStorage_, _EnvService_) => {
    $rootScope = _$rootScope_;
    $http = _$http_;
    EnvService = _EnvService_;
    makeController = () => {
      return new TeamsController();
    };
  }));

  describe('Module', () => {
    // top-level specs: i.e., routes, injection, naming
  });

  describe('Controller', () => {
    // controller specs
    it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller
      let controller = makeController();
      expect(controller).to.have.property('name');
    });
  });

  describe('Template', () => {
    // template specs
    // tip: use regex to ensure correct bindings are used e.g., {{  }}
    it('has name in template [REMOVE]', () => {
      // expect(TeamsTemplate).to.match(/{{\s?vm\.name\s?}}/g);
    });
  });

  describe('Component', () => {
      // component/directive specs
      let component = TeamsComponent;

      it('includes the intended template',() => {
        expect(component.template).to.equal(TeamsTemplate);
      });

      it('uses `controllerAs` syntax', () => {
        expect(component).to.have.property('controllerAs');
      });

      it('invokes the right controller', () => {
        expect(component.controller).to.equal(TeamsController);
      });
  });
});
//---------- ...\client\app\services\services.js ----------
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import 'ngstorage';

import env from './env';
import security from './security';
import auth from './auth';
import events from './events';
import teams from './teams';
import companies from './companies';
import profile from './profile';
import common from './common';


export default angular
  .module('app.services', [])
  .service({
    env,
    security,
    auth,
    events,
    teams,
    companies,
    profile,
    common,
  })


---------- ...\client\app\services\env.js ----------
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import 'ngstorage';

export default class EnvService {
  constructor($http, $localStorage, $state, $q) {
    this.$http = $http;
    this.$localStorage = $localStorage;
    this.$state = $state;
    this.$q = $q;

  }

  getAPIEndPoint() {
    // return 'https://dev.int.jobbleapp.com/jobbleapi/';
    return 'https://jbl-qa-api.int.jobbleapp.com/jobbleapi/';
  }

  getTransActionFee() {
    return 0.05;
  }

}

EnvService.$inject = ['$http', '$localStorage', '$state', '$q'];

Could you let me know what the problem is?

I am really appreciate if you provide a unit test example with injecting a custom angular service.

Thanks

Issue Analytics

  • State:open
  • Created 7 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
ttbarnescommented, Jul 28, 2016

@pziegler @samithaf Yes, the confusion has been that @calemyers723 wasn’t sure how to inject a service into a unit test. Mocking a service is great, but you can also inject and mock, for example some service methods.

I think it’s worth putting in an example of injecting a service, with or without with mocking.

0reactions
samithafcommented, Jul 28, 2016

@pziegler @ttbarnes yup. as per my original comment, i was suggesting to use Angular component controller for unit tests. Component controller facilitate to write unit tests with ease! Also you can mock the entire service easily as follows.

describe('Controller', () => {
    beforeEach(() => {
      // mock login service
      const mockLoginService = () => {
        const service = {
          login: (form) => {
            const deferred = $q.defer();
            if (form.username === 'david') {
              deferred.resolve();
            } else {
              deferred.reject({ status: 403, reason: 'invalid user' });
            }

            return deferred.promise;
          },

          invalidateSession: () => {},
        };

        return service;
      };

      // mock user service
      const mockUserService = () => {
        const service = {
          fetchProfile: () => {
            const deferred = $q.defer();
            deferred.resolve();
            return deferred.promise;
          },
        };

        return service;
      };

      // use $componentController helper to init the controller
      // https://docs.angularjs.org/api/ngMock/service/$componentController
      controller = $componentController('login', {
        $q,
        $scope: $rootScope.$new(),
        loginService: mockLoginService(),
        userService: mockUserService(),
      });
    });

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Test using Karma for the controller with Service · Issue #146
I have created one angularjs service and tried to inject in my teams.spec.js for unit test. But I get the error like this....
Read more >
Unit Testing AngularJS Controllers using Karma and Jasmine
Jasmine with Karma provides a command line utility to unit test the Angular Controller without requiring DOM. Download the entire source code of ......
Read more >
Angular: Unit Testing Jasmine, Karma | by Jagadish Hiremath
Karma is a JavaScript command-line tool that can be used to spawn a web server which loads your application's source code and executes...
Read more >
AngularJS Unit Testing With Karma & Jasmine
Unit tests for an existing reference Angular application + how to make good use of testing tools for Angular.
Read more >
Testing Module,controllers and Factory Service using Jasmine ...
If the Factory service for which am writing the Unit test case has dependency on other services, should those services also be mocked...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found