在AngularJS中的服务内部模拟服务

时间:2017-08-22 15:40:01

标签: javascript angularjs jasmine mocking karma-runner

我有以下服务:

DataService.js

app.service("DataService", [
  function () {
    this.getData = function () { return "original value" }
  }
]);

LocationService.js

app.service("LocationService", ["DataService", 
  function(dataSvc) {
    this.getLocationData = function () {
      return dataSvc.getData();
    }
  }
]);

现在测试LocationService.js,如何在LocationService中模拟DataService?

这是我目前对LocationService_tests.js所拥有的:

describe("LocationService", function () {
  var locationSvc;
  beforeEach(module('myModule'));
  beforeEach(inject(function (LocationService) {
    locationSvc = LocationService;
  }));

  describe("getLocationData", function () {
    it("returns the location data", function () {
      var mockLocationDataValue = "mocked value";
      // ???
      // I want to mock dataSvc.getData within getLocationData
      //  so it returns "mocked value" instead of "original value"
      expect(locationSvc.getLocationData()).toBe(mockLocationDataValue);
    });
  });
});

1 个答案:

答案 0 :(得分:3)

您可以使用$provide API service方法模拟整个服务,并将service更改为已返回mock data

describe("LocationService", function () {
  var locationSvc;
  beforeEach(module('myModule'));
  beforeEach(module(function($provide) {
     $provide.service('LocationService', function() {
       this.getData = function() {
          return "mock value";
       }
     });
  });

  beforeEach(inject(function (LocationService) {
    locationSvc = LocationService;
  }));
  ...
});