jqueryangularjshttpbackendangular-mockangularjs-ngmock

$httpBackend does not mock $.ajax(...) calls


Trying to create a mock for $.ajax calls using $httpBackend.

The below mocking snippet worked fine for worked fine with $http.get('/phones')

$httpBackend.whenGET('/phones')

But when tried to use the same for

$.ajax({
       url: '/phones',
       type: 'GET'
})

This threw a 404 error for the '/phones' ajax call.

Jsfiddler link here.


Solution

  • As the first line of the $httpBackend documentation states, $httpBackend is a

    Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

    If you don't use the $http service, then $httpBackend will not know about the request, and hence will not be able to intercept it or mock a response.

    You should always use $http - there's no reason to use $.ajax in an angular app.