What's the best way to mock / stub $ localForage in AngularJS tests?

I want to test Factory and it uses $ localForage. What's the best way to test methods inside my Factory? Let's assume the Karma config is ok.

Check out the example below:

./test/specifications/fabrics/UX-event.js

    'use strict';

    describe('Service: uxEventFactory', function () {
      beforeEach(module('paxApp'));

      var uxEventFactory;
      beforeEach(inject(function (_uxEventFactory_) {
        uxEventFactory = _uxEventFactory_;
      }));

      it('gets an instance of uxEventFactory', function () {
        expect(uxEventFactory).toBeDefined();
      });

      it('enqueues the item in the database', function () {
        var key = uxEventFactory.enqueue('1', '2', '3', '4');
        expect($localForage.getItem(key)).toBe({
          name: '1',
          action: '2',
          label: '3',
          value: '4'
        });
      });
    });

      

./application/scripts/factories/UX-event.js

    'use strict';

    /**
     * @ngdoc service
     * @name paxApp.uxEventFactory
     * @description
     * # uxEventFactory
     * Factory in the paxApp.
     */
    angular.module('paxApp')
      .factory('uxEventFactory', function ($localForage) {
        return {
          enqueue: function (name, action, label, value) {
            var uxEvent = {
              name: name,
              action: action,
              label: label,
              value: value
            };
            var key = 'uxevent-' + new Date().getTime();
            $localForage.setItem(key, uxEvent);
            return key;
          }
        };
      });

      

+3


source to share





All Articles