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

标签 angularjs karma-jasmine

按照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/

相关文章:

CSS Bootstrap AngularJS - 如何降低表格行高?

javascript - 如何使用 ui-router 将子状态或孙状态设置为默认索引状态?

c# - 将多个对象从 Angular Controller 发布到 Web API 2

npm - 错误 : No provider for "framework:jasmine"!(正在解析:框架:jasmine)

javascript - Angular 指令中无限嵌套的 ng-repeat

javascript - 在我的例子中如何从指令中获取值

unit-testing - vuejs中的单元测试

Angular 2 - 如何模拟组件中调用的服务?

angularjs - 模拟 promise 链函数

Angular 单元测试 - 成功构建后启动 Chrome(需要很长时间)