Angularjs Jasmine中的$http mock导致角度服务测试失败
我正在尝试测试一个包装API调用的Angular服务。为了测试,我使用了Angularjs Jasmine中的$http mock导致角度服务测试失败,angularjs,jasmine,karma-runner,Angularjs,Jasmine,Karma Runner,我正在尝试测试一个包装API调用的Angular服务。为了测试,我使用了Jasmine和Karma。我的测试如下所示: describe('$http basic', function () { var ConcernService, $httpBackend, $scope; beforeEach(module('concernsApp')); beforeEach(inject(function ($injector) { ConcernService = $inj
Jasmine
和Karma
。我的测试如下所示:
describe('$http basic', function () {
var ConcernService, $httpBackend, $scope;
beforeEach(module('concernsApp'));
beforeEach(inject(function ($injector) {
ConcernService = $injector.get('ConcernService');
$httpBackend = $injector.get('$httpBackend');
$scope = $injector.get('$rootScope').$new();
var projects = [{"id": 2, "title": "FooProject", "created_by": 1}, {"id": 5, "title": "BarProject", "created_by": 1}];
$httpBackend.whenGET('http://localhost:8000/api/projects')
.respond(projects);
}));
it('should return all projects', function () {
ConcernService.list('projects')
.then(function(data) {
expect(data.length).toEqual(2);
});
$scope.$apply();
$httpBackend.flush();
});
此操作失败,给我一个ConcernService
是未定义的错误
我已尝试将Concernservice
模块直接注入测试:
...
it('should return all projects', function () {
inject(function(ConcernService) {
ConcernService.list('projects')
.then(function(data) {
expect(data.length).toEqual(2);
});
$scope.$apply();
$httpBackend.flush();
});
});
但是现在我得到了一个moduler
,大概来自未知的'ConcernService'模块
我做错了什么
编辑
我们使用这种方法进行测试,请尝试:
beforeEach(module('concernsApp'));
beforeEach(inject(function (ConcernService) {
...
}));
好的,所以我最终找到了问题的根源,在离开它并回来之后;) 解决方案是双重的。我决定更换Karma正在运行的浏览器(我在Debian上,最容易连接的浏览器是FF)。我换了Chrome浏览器,突然收到了更好的错误信息。当FF只声明
ConcernService
未定义时,Chrome通知我缺少某些依赖项(本地js文件)。一旦我纠正了这些,我所有的测试都通过了
感谢所有花时间帮助我的人。我发布这个答案只是希望对其他人有用。ConcernService在哪里以及如何定义?它不是在
$injector
中定义的吗?向我们展示定义ConcernService的代码。编辑:显示服务代码。1.2.3:您的意思是在$injector
之外注入服务吗?
beforeEach(module('concernsApp'));
beforeEach(inject(function (ConcernService) {
...
}));