如何在模拟该服务的依赖项时测试角度服务?

时间:2014-01-24 21:20:02

标签: angularjs testing

所以我有两项服务:

// The service I'm testing
angular.module("m").service("myService", function(otherService) { ... })

// the service I'd like to mock while testing
angular.module("m").service("otherService", function() { ... })


describe("my test", function() {

  var myService = null;

  beforeEach(module('m'));
  beforeEach(inject(function($injector) {
     ///////////////////////////////////////////////////////
     // but I want it to get injected with 'otherService'
     ///////////////////////////////////////////////////////
     myService = $injector.get("myService")
  })

  it ('test myService', function() {

  })   
})

我想在注入otherService之前模拟myService,然后在后续myService函数中测试it的实例。

2 个答案:

答案 0 :(得分:0)

您可以动态模拟有问题的服务方法

var myService, otherService;

beforeEach(inject(function($injector) {
  myService = $injector.get('myService');
  otherService = $injector.get('otherService');
}));

it('calls otherService.doOther when doSomething is called', function() {
  spyOn(otherService, 'doOther');
  myService.doSomething();
  expect(otherService.doOther).toHaveBeenCalled();
});

使用茉莉花间谍,您可以测试具有不同返回值的结果等。

it('doesSomething returns true when otherService.doOther returns false', function() {
  spyOn(otherService, 'doOther').andReturn(false);
  expect(myService.doSomething()).toBeTruthy();
});

答案 1 :(得分:0)

您应该使用$provide服务将otherService实施替换为模拟实现。你走了:

describe('my test', function() {
    var myService, otherServiceMock;

    beforeEach(function() {
        module('m');

        otherServiceMock = jasmine.createSpyObj('otherService', [...]);

        module(function($provide) {
            // Replaces the service with a mock object
            $provide.value('otherService', otherServiceMock);
        });

        inject(function(_myService_) {
            myService = _myService_;
        });
    });
});

查看$provide文档以获取更多信息。