2

I am using the book called AngularJS Up and Running. It gives an example of using exceptGET. This is the example:

mockBackend = $httpBackend;
mockBackend.exceptGET('/api/note')
    .respond([{id:1, label: 'Mock'}]);

My question is, isn't the point of unittesting server calls to make the server call and verify that the server call is what we expect it to be?

With the above code, does it not just make a server call and force the response to equal [{id:1, label: 'Mock'}]? What's the point of doing it if we aren't able to check what the actual response is?

Because later on in the code, it checks the response like so:

mockBackend.flush();
expect(ctrl.items).toEqual([{id:1, label: 'Mock'}]);

Wouldn't it Always equal [{id:1, label: 'Mock'}] because that's what we forced the response to equal? What's the benefit of having .respond() and controlling the response?

SilentDev
  • 20,997
  • 28
  • 111
  • 214

1 Answers1

1

If you would actually hit an API endpoint on the server in your unit test, it would not be a unit test anymore - it would now involve much more than just your component under test (controller/service/provider etc) - the network, the web server, the backend itself, probably a database etc - now this becomes an integration test or a system/functional test.

Your unit test would not be isolated anymore and would depend on more things than it should. The point of mocking is to make the test isolated, independent and imitate certain desired conditions - in this case an HTTP response - and then check how your component under test would react.

expect(ctrl.items).toEqual([{id:1, label: 'Mock'}]);

This expect call itself, at least, would check that the mock was successfully applied and the items controller variable contains the mocked response.

Please see more at:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • @alecxa Okay so just to verify, when a user goes to `/api/note`, it does one of two things: 1) If the response is successful, it makes `items` equal to the response. 2) If the response is not successful and raises an error, it makes the ctrl.errorMessage equal to the response. In testing, when I do `mockBackend = $httpBackend; mockBackend.exceptGET('/api/note').respond([{id:1, label: 'Mock'}]);`, I basically am testing if the 1st case runs correctly (that `items` is indeed equal to `[{id:1, label: 'Mock'}]`), right? – SilentDev Jan 05 '16 at 22:39
  • @user2719875 yes, and turn the coverage reporter on so that you can actually see what parts of the controller were covered by the test. Hope the answer helps.. – alecxe Jan 05 '16 at 22:42