2

We have a set of test cases which is common for many different forms. Some of the forms may trigger a lazy loader which would prefetch some data in their post section of the directive, so firing a HTTP GET.

In the common test's beforeEach, I thus have to handle it, else I get Unexpected request: GET /bla/requests/generateJson/something No more request expected

I added $httpBackend.when("GET",//generateJson/(.+)/).respond(); before scope.$digest(); in the test's beforeEach. Now, the error changes to

Error: Unflushed requests: 1

Adding $httpBackend.flush();

causes the test cases when the GET call is fired to pass, but all test cases which do not fire a GET, fail with error

Error: No pending request to flush !

How can I handle that? I just want this test to ignore the GET completely, whether it is present or not. Can I somehow determine if the GET was fired, and so react with flush?

Petr Osipov
  • 621
  • 6
  • 16

1 Answers1

0

You can verify that no calls were made to the $httpBackend mock with the verifyNoOutstandingRequest() method. You can also verify that any expected calls to the backend were successful with the verifyNoOutstandingExpectation() method. So you code would look something like this:

describe('Test HTTP Service', function () {

    var $httpBackend;

    beforeEach(inject(function (_$httpBackend_) {
        $httpBackend = _$httpBackend_;
        $httpBackend.when('GET', '//generateJson/(.+)/').respond();
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('calls the backend', function () {
        $httpBackend.GET('//generateJson/Petr/');
        $httpBackend.flush();
    });

    it('does not call the backend', function () {
        // Some action that does call $httpBackend
    });

});

More information can be found on the $httpBackend docs page. Also, check out this discussion over on GitHUb.

Drewness
  • 5,004
  • 4
  • 32
  • 50