mercredi 2 décembre 2015

Mocking a service in jasmine: missing provider

I am very new to unit testing. I am working on a code. My js file has:

app.service("appService", function($http) {
  this.getData = function(url) {
    return $http.get(url);
  }

  this.foo = function() {
    console.log("Hello foo function");
  }
})

app.controller("productsController", ['$scope', '$http', 'appService',
  function($scope, $http, appService) {
    var pct = this;
    console.log("This is products controller");
    pct.url = "http://ift.tt/1IGg6po";
    var jsonDataPromise = appService.getData(pct.url);
    jsonDataPromise
      .then(function(response) {
        pct.jsonData = response.data;
      }, function(err) {
        console.log("Error is: " + error);
      });
  }
]);

I am unit testing it in karma.js using jasmine framework. I have made testfile.js as:

describe('unitTesting', function() {
  var $prodScope, prodCtrl, mockService;
  beforeEach(module('sampleApp')); //Name of angular module 
  var jsonData = {
    "name": "test_name",
    "email": "test_email"
  };

  beforeEach(function() {
    mockService = jasmine.createSpyObj('appService', ['getData', 'foo']);
  })

  beforeEach(inject(function($controller, $rootScope, $httpBackend, $http, $q, mockService) {
    defer = $q.defer();
    $prodScope = $rootScope.$new();
    prodCtrl = $controller('productsController', {
      $scope: $prodScope,
      $http: $http,
      appService: mockService
    });

    spyOn(mockService, "getData").and.callFake(function() {
      return defer.promise;
    });
    spyOn(mockService, "foo");

  }));

  //Here unit tests go

})

My issue is that when I run the tests using karma start (I am having karma.conf.js), I get error:

[$injector:unpr]Unknown provider: mockServiceProvider <- mockService.

Can anyone explain to me why I am getting this error? Please explain what should be the correct code.

Aucun commentaire:

Enregistrer un commentaire