Kanissell Kanissell - 4 years ago 106
AngularJS Question

How to mock $cookiestore.put in AngularJS/Jasmine

I want to test my Authentication.Login service function.

In this service is call of another service and a cookiestore.put method.

I want to mock both function. But Im still get a error :/

I have try it with the spyon Function in Jasmine, but it doesnt work :

spyOn('base64', 'encode').and.returnValue(username + ';' + password);
spyOn('cookie', 'put').and.returnValue(username);

Can anybody help me ?

this is the authentication service :

function (Base64, $http, $cookieStore, $rootScope, $q) {
//initialize service
var service = {};

service.Login = function (username, password) {
//initialize promise object for asynchron behavior of the data
var deferred = $q.defer();

var authdata = Base64.encode(username + ':' + password);

//put login data in global variable to access in the root scope
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata

//put base64 data in header
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
//put login data in cookie to keep user logged in, if he refresh the page
$cookieStore.put('globals', $rootScope.globals);

Answer Source

Override service using $provide:

var cookieStoreMock = {
  put: function() {
    return username;

module(function($provide) {
  $provide.value('$cookieStore', cookieStoreMock);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download