我的测试是:
'use strict';
(function() {
describe('Service: Summary', function () {
var $httpBackend;
// load the service's module
beforeEach(module('mean'));
var SummaryService;
beforeEach(inject(function($injector, _SummaryService_) {
SummaryService = _SummaryService_;
$httpBackend = $injector.get('$httpBackend');
}));
// instantiate service
it('should do something', function () {
expect(!!SummaryService).toBe(true);
});
it('should get a summary', function () {
$httpBackend.expectGET('/api/ABC').respond(200);
SummaryService.get();
});
});
})();
我的服务是:
'use strict';
angular.module('mean')
.service('SummaryService', ['$http', function SummaryService($http) {
var summary = this;
summary.get = function () {
return $http.get('/api/summary');
};
}]);
正如您所看到的,它应该转到/api/summary
而不是/api/ABC
,但测试仍然通过。我做错了什么?
答案 0 :(得分:1)
我建议您将以下代码添加到测试中:
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
第一个将确保您已定义的所有期望。在您的情况下,$httpBackend.expectGET('/api/ABC')
是一个未完成的未完成请求。
第二个将确保没有更多请求未被刷新。在您的情况下,$http.get('/api/summary')
永远不会被刷新。
事实上,在您的测试中,您没有测试请求。通常的测试用例如下:
您可以更改#2和#3的顺序,因为在调用$httpBackend.flush()
之前不会发生后端调用。
有关详细信息,请参阅$httpBackend。