Pregunta

I am trying to test an Angular service. I have a constant called keys. I am trying to mock out this constant, but I continue to get the real constant. Here is my test:

  describe('getSuperheroes()', function() {
    var mockKeys;
    beforeEach(function() {
      mockKeys = sinon.stub({apikey: 'test'});
      module(function($provide) {
        $provide.value('keys', mockKeys);
      });
    });
    it('should populate superheroes[] with result from get()', inject(function(superheroService, $httpBackend) {
      expect(superheroService.superheroes).toBeNull();
      $httpBackend.when('GET', 'http://gateway.marvel.com/v1/public/characters?apikey=test').respond({
        data: {
          results: 100
        }
      });
      superheroService.getSuperheroes();
      $httpBackend.flush();
      expect(superheroService.superheroes).toBe(100);
    }));

Here is my keys module:

angular.module('marvelApp').constant('keys', {
  apikey: 'vip number'
});

And here is my service:

angular.module('marvelApp').factory('superheroService', function($resource, $q, keys) {
  return {
    superheroes: null,
    getSuperheroes: function() {
      var deferred = $q.defer();
      var that = this;
      if(this.superheroes) {
        deferred.resolve(that.superheroes);
      } else {
        this.getResource().get({
          apikey: keys.apikey
        }, function(data) {
          that.superheroes = data.data.results;
          deferred.resolve(data.data.results);
        });
      }
      return deferred.promise;
    },
    ...
  };
});

What am I doing wrong in my test that isn't allowing me to mock out the keys module. Thanks for the help.

¿Fue útil?

Solución

The problem was that I was using the wrong method that $provide offered me. I was trying $provide.value() when the proper function should of been $provide.constant() because I was trying to mock a constant. Easy peasy.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top