角模拟$ httpBackend给没有挂起请求刷新 [英] Angular mock $httpBackend give No pending request to flush

查看:266
本文介绍了角模拟$ httpBackend给没有挂起请求刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

angularJS $ httpBackend官方指南我会做这个测试,但给噶我这个错误
错误:没有挂起请求刷新!
        在功能。$ httpBackend.flush

Following the official guide at angularJS $httpBackend I'll do this test, but Karma give me this error: 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');
});

});

对于这个简单的控制器

'use strict';

 angular.module('maap').controller('profileCtrl', function($scope, UserService) {

$scope.current_user = UserService.details(0);

});

推荐答案

_ $ httpBackend _ 无关冲洗,因为你不使你的测试任何HTTP请求

The _$httpBackend_ has nothing to flush because you don't make any http request in your test.

您需要调用一些code,使一个HTTP请求。

You need to invoke some code that make an http request.

然后,一旦一些地方在您的测试做一个HTTP请求,则可以使提供给已提出请求的响应调用刷新方法。

Then, once something somewhere made an http request in your test, you can call the flush method so that a response is provided for the request that has been made.

是这样的:

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');
});

这篇关于角模拟$ httpBackend给没有挂起请求刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆