我正在尝试使用业力编写集成测试。我需要做真正的http调用并得到实际的响应。我尝试了#1434中提到的所有解决方案,比如使用passthrough()并在angular-mocks.js中评论“$ httpBackend:angular.mock。$ HttpBackendProvider”,但没有一个能够工作。
这是我的测试代码:
use strict';
describe('module: main, service: AuthService', function () {
beforeEach(module('ngMockE2E'));
// load the service's module
beforeEach(module('main'));
// load all the templates to prevent unexpected $http requests from ui-router
beforeEach(module('ngHtml2Js'));
// instantiate service
var AuthService;
var $q;
var deferred;
var $rootScope;
var response;
var scope, http, flush, httpBackend;
beforeEach(inject(function ($httpBackend,AuthService,$q, $rootScope) {
httpBackend = $httpBackend;
AuthService = AuthService;
$q = $q;
$rootScope = $rootScope;
deferred = $q.defer();
scope = $rootScope.$new();
}));
it('should do something', function () {
expect(!!AuthService).toBe(true);
expect(AuthService).not.toBeNull();
});
it('verify authenticating user', function () {
AuthService.authUser('abc@abc.com','abc123').then(function (result) {
console.log("Result of successful auth user is ");
console.log(result);
expect(result).toEqual(true);
done();
}, function (error) {
console.log("error of failure auth user is ",error);
expect(false).toBe(true);
done();
});
httpBackend.whenPOST('/oauth/token').passThrough();
$rootScope.$digest();
//httpBackend.flush();
});
});
如果某人有任何解决方案可以在karma测试中进行真正的http调用
,那将会很棒答案 0 :(得分:0)
当Angular应用程序需要来自服务器的某些数据时,它会调用$ http服务,该服务使用$ httpBackend服务将请求发送到真实服务器。使用依赖注入,很容易注入$ httpBackend mock(它具有与$ httpBackend相同的API)并使用它来验证请求并使用一些测试数据进行响应,而无需向真实服务器发送请求。
根据您的数据尝试修改
it('verify authenticating user',
function() {
httpBackend.expect('POST', '/oauth/token')
.respond(200, "[{ success : 'true', id : 123 }]");
AuthService.authUser('abc@abc.com', 'abc123')
.then(function(data) {
expect(data.success).toBeTruthy();
});
$httpBackend.flush();
});