我有服务:
angular.module('driveby').factory('BuildingsService', function(Restangular) {
var buildings = [];
var fetchBuildings = function() {
return Restangular.all('buildings').getList();
};
var getBuildings = function() {
return buildings;
};
return {
getBuildings: getBuildings,
fetchBuildings: fetchBuildings
};
});
我正在尝试使用Jasmine进行单元测试,但承诺永远不会解决:
describe('BuildingsService', function () {
var BuildingsService, httpBackend;
var buildingsUrl = '/api/buildings';
var mockBuildings = [
{id: 1},
{id: 2},
{id: 3}
];
beforeEach(module('driveby'));
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend;
httpBackend.whenGET(buildingsUrl).respond(
JSON.stringify(mockBuildings)
);
}));
beforeEach(inject(function(_BuildingsService_) {
BuildingsService = _BuildingsService_;
}));
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('can fetch the list of buildings from the API', function() {
expect(BuildingsService.getBuildings().length).toEqual(0);
httpBackend.expectGET(buildingsUrl);
BuildingsService.fetchBuildings().then(function(buildings) {
expect(buildings.length).toEqual(3);
});
httpBackend.flush();
expect(BuildingsService.getBuildings().length).toEqual(3);
});
});
问题是该行永远不会在测试中执行:
expect(buildings.length).toEqual(3);
API路由是正确的,没有未完成的请求,但httpFlush没有解决Restangular的承诺。此行应该通过,但它返回0而不是3:
expect(BuildingsService.getBuildings().length).toEqual(3);
有人在这里看到了什么问题吗?
答案 0 :(得分:0)
承诺内部回调不起作用。测试这样的promises的正确方法是将返回值分配给promise的范围之外的变量。
您的第二个期望是返回0,因为您的服务的fetchBuildings()没有将buildings数组设置为API调用的结果;它只是回来了。您应该将该赋值添加到函数中,或者在测试中创建一个给出API调用返回值的变量,然后使用expect()进行检查;