angularjs – 角度模拟$httpBackend给予无待处理的刷新请求

前端之家收集整理的这篇文章主要介绍了angularjs – 角度模拟$httpBackend给予无待处理的刷新请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
按照 angularJS $httpBackend的官方指南,我会做这个测试,但是Karma给我这个错误
错误:无待处理的请求冲洗!
函数$ 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请求。

您需要调用一些发出http请求的代码

然后,一旦某个地方在您的测试中发出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');
});
原文链接:https://www.f2er.com/angularjs/144067.html

猜你在找的Angularjs相关文章