Jasmine : Expect $http.post() not have been called
12,567
Solution 1
That is error is because you never injected $http into the test. You can do this with the inject function, but for testing $http
calls, you really should use $httpBackend
For requests that you want to make sure they aren't called, you don't need to do anything. Angular throws an error when it gets a request that wasn't expected (as defined by the expect
functions on $httpBackend
). So If a request is made that shouldn't be, the tests will fail from this error thrown from an unexpected request.
Solution 2
This is old but I used the following to test for this.
expect($httpBackend.flush).toThrowError('No pending request to flush !');
Author by
W Lambert
Updated on July 19, 2022Comments
-
W Lambert almost 2 years
In an angularjs program I'd like to test with Jasmine if an http post is NOT performed in a test.
I've try the following code :
expect($http.post).not().toHaveBeenCalled();
But I get "ReferenceError: $http is not defined"
-
W Lambert over 10 yearsOk, in other tests I test if $http.post is called with
scope.httpBackend.expectPOST('MY_ENDPOINT', data)
which works. Now in a test I want to test that a post request is not made. I don't see any post method in $httpBackend to do kind of test :expect(scope.httpBackend.post).not.toHaveBeenCalled();
Note that in beforeEach i've inject $httpBackend in my scope :scope.httpBackend = $httpBackend;
-
dz210 over 8 yearsThis is not entirely true. If you don't call $httpBackend.flush(), you will not get an unexpected request error. If you do call $httpBackend.flush() and the request is not made, you will get a No pending request to flush error. There must be a better way.