当我和API之间的交互格式发生变化时,会出现大多数问题。我想测试与API对话的角度服务。如果此服务使用$http
,我如何将我的角度服务注入测试并获得正确的结果?我应该使用jasmine,这种类型的集成测试的单元测试工具吗?
在这个例子中,我正在测试使用OntologyService
的{{1}}并返回一个promise,测试结果如下:
$http
我收到以下错误消息:
describe('Service: OntologyService', function () {
var OntologyService, $scope;
beforeEach(function () {
module('oneClickRegistrationApp');
inject(function ($injector) {
OntologyService = $injector.get('OntologyService');
$scope = $injector.get('$rootScope').$new();
});
});
it('should return the object of ontologies', inject(function () {
var ontoServerApiUrl = 'https://myurl.com/api/ksearch/ontologies/';
OntologyService.getAllOntologies(ontoServerApiUrl).then(function (ontologies) {
expect(ontologies).toBeNonEmptyObject();
expect(ontologies["licenses"]).toHaveArrayOfObjects();
expect(ontologies["species"]).toHaveArrayOfObjects();
expect(ontologies["measurement_methods"].length).toBeGreaterThan(10);
});
$scope.$digest();
}));
});
答案 0 :(得分:1)
Error: Unexpected request: GET https://
此博客文章可为您提供帮助:http://www.bradoncode.com/blog/2015/06/16/unit-test-http-ngmock-passthrough/
... $ httpBackend服务要求我们模拟测试代码中使用的所有HTTP请求...
...做一个真正的HTTP调用以便我可以试验,获得一些JSON等示例...
... ngMock确实包含了ngMockE2E,它允许我们创建虚假的后端HTTP调用,但我们只能在完整的应用程序中使用它,即通过浏览器而不是单元测试......
以下是如何制作真实的http请求:
describe('real http tests', function() {
beforeEach(angular.mock.http.init);
afterEach(angular.mock.http.reset);
beforeEach(inject(function(_$controller_, _$httpBackend_) {
$controller = _$controller_;
$scope = {};
$httpBackend = _$httpBackend_;
// Note that this HTTP backend is ngMockE2E's, and will make a real HTTP request
$httpBackend.whenGET('http://www.omdbapi.com/?s=terminator').passThrough();
}));
it('should load default movies (with real http request)', function (done) {
var moviesController = $controller('MovieController', { $scope: $scope });
setTimeout(function() {
expect($scope.movies).not.toEqual([]);
done();
}, 1000);
});
});