chfw
chfw

Reputation: 4592

Angular Karma Unit Test: How to inject a mock service in karma configuration instead of in all test specs

Recently, I have added a security feature to an existing angular app. Here is what I got afterwards:

Chrome 3X.0.2125 (Linux) ERROR
  Some of your tests did a full page reload!
Chrome 3X.0.2125 (Linux): Executed 23 of 102 (skipped 2) ERROR 

This is how I have set up the security feature:

angular.module('myapp', [/*..I have omitted..*/])
       .run(function(MyLoginSerivce, /*.. I have omitted ..*/)){
           if(!MyLoginService.isLoggedIn()){
               MyLoginService.redirectForLogin();
           }else{
               /* other logics */
           }
       }

I knew I have to add the following code to each and every test spec. But it sounds silly adding it to dozens of test files.

  beforeEach(module(function($provide){
    $provide.value("MyLoginServce", {
      isLoggedIn: function(){
        return true;
      },
      redirectForLogin: function {}
    });
  }));

Is there a way to tell Karma that use a mock service and add that piece of code only once and in one place?

Thanks

Current solution

Step 1: I saved this in a separate file, e.g. ./test/mocked.login.service.js:

   var mockedLoginService = {
      isLoggedIn: function(){
        return true;
      },
      redirectForLogin: function {}
    });

Step 2: I include the file in karma.conf.js, by inserting 'test/mocked.login.service.js'

Step 3: I just use it in my tests like the following:

  beforeEach(module(function($provide){
    $provide.value("MyLoginServce", mockedLoginService
  }));

Upvotes: 4

Views: 1447

Answers (1)

pansay
pansay

Reputation: 687

You can extract the mocked service into a separate js file as an object, include that file in the karma.conf files list, then use that object as a global in your specs.

Upvotes: 3

Related Questions