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.
Does that mean, if there are
n
same api calls in a particular code stub, I have to expect themn
number of times ?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:
Use of
expect
:- Expects the order of the API call. It expects that the code should call the api's in the exact order that you expect.
- If there are 3 api calls, then you should expect them 3 times.
Use of
when
: ($httpBackend.when)- Does not expect if an API call is made or not. Just doesn't throw any error.
$httpBackend.when
behaves like a mini mock database. Whenever your code, expects some response from an API, supply it. Thats it.