gpt4 book ai didi

angularjs - Angular 模拟$ httpBackend没有给出任何刷新请求

转载 作者:行者123 更新时间:2023-12-03 12:29:03 27 4
gpt4 key购买 nike

按照angularJS $httpBackend的官方指南,我将进行此测试,但Karma会给我这个错误:Error: No pending request to flush !
at Function.$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');
});

});

对于这个简单的 Controller :
'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');
});

关于angularjs - Angular 模拟$ httpBackend没有给出任何刷新请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22226160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com