使用jasmine进行测试时,未定义注入的服务

时间:2015-09-28 11:41:35

标签: angularjs service karma-jasmine

出于某种原因,当我运行测试时,Jasmine告诉我“DataFactory”未定义。有什么想法吗?

angular.module('MyApp')
.factory('DataFactory', ['$http', function($http){
    return {
        getArtists: function(){
            return $http.get('artists.json');   
        }
    }
}]);

});

findAll()

2 个答案:

答案 0 :(得分:0)

要获得支持,您必须显示定义DataFactory的代码!

在这里,我看到另一个错字:

expect(DataFactory.getArtists).toHaveBeenCalled();
expect(dataFactory.getArtists.callCount).toEqual(1); <-- DataFactory instead of dataFactory

答案 1 :(得分:0)

您需要在测试中定义DataFactory。

这样做。

describe('Practice', function(){
 var ctrl;
 var DataFactory;

 beforeEach(module('MyApp'));
 beforeEach(inject(function($controller, _DataFactory_){
    DataFactory = _DataFactory_;
    spyOn(DataFactory, 'getArtists').andCallThrough();
    ctrl = $controller('ArtistCtrl', {
      DataFactory: DataFactory
    });   
}));

it('should have array available on load', function(){
    expect(DataFactory.getArtists).toHaveBeenCalled();
    expect(DataFactory.getArtists.callCount).toEqual(1);
});