2

我正在尝试在我的 AngularJS 项目中测试服务。我要做的就是查看我的服务上的方法是否已调用。我认为当您在 jasmine 中使用“and.callThrough()”时,它会为您调用该方法,然后您可以查看它是否被调用。但是,当我测试我的功能时,业力给了我“预计 getArtists 的间谍已被调用”的响应。

describe('Practice', function(){
 beforeEach(module('MyApp'));
 var ctrl, loadArtists, rootscope, dataFactory;
 beforeEach(inject(function($controller, $rootScope, DataFactory){
    spyOn(DataFactory, 'getArtists').and.callThrough();
    dataFactory = DataFactory
    rootscope = $rootScope;
    scope = rootscope.$new();
    ctrl = $controller('LaunchCtrl',{scope: scope, artistsPicsRotate: []});
}));

it('should do nothing',function(){
    expect(ctrl.artistsPicsRotate).toEqual([])
});

it('should call through DataFactory', function(){
    expect(dataFactory.getArtists).toHaveBeenCalled();
    expect(dataFactory.getArtists.calls.count()).toEqual(1);
});

});

任何关于为什么这不起作用的想法将不胜感激。

4

1 回答 1

2

正如评论中所解释的,对服务的调用是由ui-router在实例化控制器之前解析完成的。这意味着控制器永远不会显式调用 DataService.getArtists(),因为当路由状态被解析并且接收到的结果被注入控制器时调用就完成了。因此,在测试控制器时,无需测试对服务的调用,因为该调用不是直接从它发出的。

但是,如果您想测试状态定义,这里是一个示例,您可以如何做到这一点。

describe('Practice', function(){
  beforeEach(module('MyApp'));
  var ctrl, loadArtists, rootscope, dataFactory, $state;
  beforeEach(inject(function($controller, $rootScope, DataFactory, _$state_){
    dataFactory = DataFactory
    rootscope = $rootScope;
    scope = rootscope.$new();
    $state = _$state_;
    ctrl = $controller('LaunchCtrl',{scope: scope, artistsPicsRotate: []});
  }));

  it('should do nothing',function(){
      expect(ctrl.artistsPicsRotate).toEqual([])
  });

  // NOTE: test your state definition
  describe('state definition', function () {

    var stateDefinition;
    beforeEach(function () {
      stateDefinition = $state.get('stateName');
    });

    // NOTE: write test for each resolve
    it('should resolve artists', function() {
      // given
      spyOn(dataFactory, 'getArtists').and.callThrough();

      // when
      var artists = stateDefinition.resolve.artistsPicsRotate();

      // then
      expect(artists).toBeDefined();
      expect(dataFactory.getArtists).toHaveBeenCalled();
      expect(dataFactory.getArtists.calls.count()).toEqual(1);
    });  
  });
});
于 2015-10-10T10:54:24.920 回答