What is the difference between expect and when in $httpBackend
Asked Answered
P

1

24

What is the difference between $httpBackend.when('') and $httpBackend.expect('')?

I don't know the difference between these two methods. Also the angularjs api doc does not help me.

API documentation link: https://docs.angularjs.org/api/ngMock/service/$httpBackend

Pericycle answered 14/1, 2015 at 14:54 Comment(0)
H
25

$httpBackend.expect - specifies a request expectation
$httpBackend.when - specifies a backend definition

From: https://docs.angularjs.org/api/ngMock/service/$httpBackend
Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.

Backend definitions allow you to define a fake backend for your application which doesn't assert if a particular request was made or not, it just returns a trained response if a request is made. The test will pass whether or not the request gets made during testing.

Therefore, it means that if you set a request expectation with expect the test will fail if you don't get the exact same request, exact number of times. However if you set it with when, the backend will respond appropriately, but it has no expectations about how many requests (if any) will come therefore will not fail the test.

Herra answered 14/1, 2015 at 15:0 Comment(2)
It still feels unclear. should 'when' be used like: "(when ever) the app asks for 'some backend thing' just give it this"Runthrough
Expect will throw if the request doesn't match the expectation and hence fail the test. 'When' has no expectation, it will appropriately respond to requests, but will not fail if no request arrives. Use 'expect' if you want to assert the request comes in a certain format; use 'when' if you don't care about the request.Stinking

© 2022 - 2024 — McMap. All rights reserved.