Search code examples
angularjsunit-testingkarma-jasminelocalforage

How to create a mock for LocalForage.getItem() method in jasmin-karma unit tests?


What is the best way to mock localForage.getItem method? I just need to simply return a sample object when localForage.getItem is called.


Solution

  • The first thing is to wrap the third party library in an injectable service so you can swap for a mock implementation in your tests

    app.factory('localForage',function(){
      //likely coming from global namesapce 
      return localForage;
    });

    This then can be injected in directives, services, controller etc

    //example with controller
    
    myApp.controller('myCtrl',['localForage',function(localForage){
       this.getItem = localForage.getItem;
       this.setItem = loaclForage.setItem;
    }]);

    Now the idea is to replace the normal implementation by a mock in your tests. There are several ways of doing it:

    • globally: you create a mock module before running your tests which will define the mock implementation for all your tests, you will call(beforeEach(module('myMockModule'))) instead of the actual localForage module

    • on a test suite base: "$provide" a different implementation before you run the tests:

    beforeEach(module('myModule',function($provide){
      $provide.factory('localForage', function(){
        return MockImpl;
      });
    });

    • In some cases you can inject directly your mock implementation:

    var ctrl;
    
    beforeEach(inject(function($controller){
       ctrl = $controller('myCtrl',{localForage:mockImpl});
    }))

    Now about the mock implementation it depends what you want to do with it (spy it, stub, other things) but the idea is to make it implement the same api than the actual service

    var mockImpl = {
       getItem : angular.noop,
       setItem : angular.noop
    }

    This simple one will be fine for example if you want to check if the localForage is called and with which arguments (use spyOn(mockImpl, 'getItem'))