按照
angularJS $httpBackend的官方指南,我会做这个测试,但是Karma给我这个错误:
错误:无待处理的请求冲洗!
在函数$ httpBackend.flush
错误:无待处理的请求冲洗!
在函数$ httpBackend.flush
测试
'use strict'; describe('profileCtrl',function () { var scope,$httpBackend; beforeEach(angular.mock.module('maap')); beforeEach(angular.mock.inject(function($rootScope,$controller,_$httpBackend_){ $httpBackend = _$httpBackend_; $httpBackend.when('GET','profile').respond([{id: 1,name: 'Bob'}]); scope = $rootScope.$new(); $controller('profileCtrl',{$scope: scope}); })) it('should fetch list of users',function(){ $httpBackend.flush(); expectGET(scope.current_user.length).toBe(1); expect(scope.current_user[0].name).toBe('Bob'); });
});
对于这个简单的控制器:
'use strict'; angular.module('maap').controller('profileCtrl',function($scope,UserService) { $scope.current_user = UserService.details(0);
});
_ $ httpBackend_无法刷新,因为您的测试中没有发出任何http请求。
原文链接:https://www.f2er.com/angularjs/144067.html然后,一旦某个地方在您的测试中发出http请求,您可以调用flush方法,以便为已经创建的请求提供响应。
就像是:
it('should fetch list of users',function(){ // Do something that will make an http request MyService.getAllUser(function ...) // for example // Then provide a response for the http request that // has been made when getAllUser was called $httpBackend.flush(); // Check the expected result. expect(something).toBe('Bob'); });