Angularjs testing (Jasmine) - $http returning 'No pending request to flush'

怎甘沉沦 提交于 2019-12-01 23:57:30

There is a discussion about this here. "Since promises are async you need to do $rootScope.$digest() in your tests to get them going"

add this before your $httpBackend.flush():

if(!$rootScope.$$phase) {
    $rootScope.$apply();
}

so your code becomes:

it('UserManager should refresh the token after 2 seconds', inject(function(UserManager, $httpBackend) {
    UserManager.oauth.Login('gtest','qweqwe');

    if(!$rootScope.$$phase) {
        $rootScope.$apply();
    }

    $httpBackend.flush();
    expect(UserManager.oauth.credentials.access_token).toEqual('ef235de46dba53ba69ed049f57496ec902da5d28AAFB1HdeTE-2vwnhn0s-nUFtoGtj9rSm9waiuhySCpFJxKVYqOx9W7Gt');
}));

I guess you have to wrap the code below the waits inside a runs(...) block. Otherwise your code is executed immediately before the waiting has been finished

    waits(4000);
    runs(function() {
        $httpBackend.flush();
        expect(UserManager.oauth.credentials.access_token).toEqual('ef235de46dba53ba69ed049f57496ec902        da5d28AAFB1HdeTE-2vwnhn0s-nUFtoGtj9rSm9waiuhySCpFJxKVYqOx9W7Gt');
    });

It's described in the jasmine docs as well: https://github.com/pivotal/jasmine/wiki/Asynchronous-specs

Your first $httpBackend.flush() flushes all the pending requests that you defined in your beforeEach().

When you call $httpBackend.flush() a second time, there are no pending requests, so you get the message.

You need to add another event(s) after the first flush.

Untested, but that's my theory.

So with my jasmine tests all the time sometimes I have had to use regex to make the url a little less specific, most of this has been with angular wanting to strip trailing slashes or other stupid little things. Such as the request url wouldn't find the expect request but the regex below would.

https://qa.com/sessions/5cdec5bde6a242dca2cf5dd0ff7be2c9

/(qa.com\/sessions\/5cdec5bde6a242dca2cf5dd0ff7be2c9)/g
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!