0

One of my angularjs files had a code construct similar to the below:

this.examplecall = function() {
         var a = apiconfig.getconfig();
         ....
         //some lines of code
         ....
         var b = apiconfig.getconfig();
}

And I started to write unit tests for it through angular spec - Jasmine, ended up with the below stub of code.

    describe("test examplecall")...

    it("should test cofig call in examplecall", function() {

     $httpBackend.expectGET(GET_CONFIG).respond(200);

    });

The above code throws exception telling "unexpected GET.."

When I added an extra expectGET, things worked out fine. See below:

describe("test examplecall")...

    it("should test cofig call in examplecall", function() {

     $httpBackend.expectGET(GET_CONFIG).respond(200);
     $httpBackend.expectGET(GET_CONFIG).respond(200);

    });

From this, I infer that if there are two api calls in a particular function, then I have to expect it two times.

  1. Does that mean, if there are n same api calls in a particular code stub, I have to expect them n number of times ?

  2. Are there any similar constructs like,

    $httpBackend.WheneverexpectGET(GET_CONFIG).respond(200);

so, whenever we call a API just return 200 status like above?

Thank you for your comments on this...

EDIT: (read the accepted answer before going through this.)

Thanks to @kamituel for the wonderful answer.

To summarise with the information provided in his answer:

  1. Use of expect :

    1. Expects the order of the API call. It expects that the code should call the api's in the exact order that you expect.
    2. If there are 3 api calls, then you should expect them 3 times.
  2. Use of when : ($httpBackend.when)

    1. Does not expect if an API call is made or not. Just doesn't throw any error.
    2. $httpBackend.when behaves like a mini mock database. Whenever your code, expects some response from an API, supply it. Thats it.

1 Answers1

1

Yes, .expectGET is used to assert that a given request has been made by the application. So you need to call it n times if you expect the application to make n requests.

If you don't need to assert on that, but only want to make application logic work through any requests it makes, you might want to use .whenGET instead. Difference between .expectXXX and .whenXXX has been already described in another answer.

Edit: not sure which Angular version are you using, but you will find this in the implementation of .expectGET:

expectations.shift();

This is invoked once a request is made and matches what was expected. Which means the same expectation is only asserted on once.

It's usually also a good idea to call .verifyNoOutstandingExpectation() after your test is done, to ensure that each request you specified as epxected using .expectXXX() has indeed been made by the application.

Community
  • 1
  • 1
kamituel
  • 34,606
  • 6
  • 81
  • 98