lundi 30 mars 2015

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


Aucun commentaire:

Enregistrer un commentaire