mardi 25 août 2015

Angular.js unit testing - trouble mocking $window

I made a simple Angular service to interact with local storage. It has a has method that returns true/false, depending on if the key exists in local storage.

angular.module("LSmodule", [])
.service("localStorageService", ["$window", function($window){

  this.has = function(key){
    console.log($window); //added to see what $window is referencing in unit test
    if ($window.localStorage.getItem(key) !== null){
      return true;
    } else {
      return false;
    }
  };
}]);

I'm having trouble mocking out $window in my unit test. The unit test still seems to be accessing the global window object and not accessing the mock.

Here is my unit test for this service. I tried to create a mock $window object, with a getItem function.

describe("Has function", function(){
  var localStorageService;

  beforeEach(module('jbLocalStorage'), function($provide){
    $provide.value('$window', {
      localStorage : {
        getItem : function(key){
          if (key === "shape") {return "triangle";} else {return null;}
        },
      },
    });
  });

  beforeEach(inject(function(_localStorageService_){
    localStorageService = _localStorageService_;
  }));

  it("should return true if key is found in local storage", function(){
    expect(localStorageService.has("shape")).toEqual(true);
  });
});

My test fails, because the test seems to look at the global window object and doesn't find "shape", instead of looking in the mock and finding "shape".

I know it's doing this, because the console.log line in the service shows that it's still referencing the global windowobject, not the mock.

What am I doing wrong? Why is my mock not working?

Aucun commentaire:

Enregistrer un commentaire