Question

I have an AngularJS application, which needs file uploads, and as $http does not support the special features of XMLHttpRequest.upload, I have to perform the file upload using an XMLHttpRequest.

My question is: Can I use the $httpBackend to unit test the requests made via new XMLHttpRequest()?

I have some tests made, but at the moment $httpBackend is throwing errors. Without calling $httpBackend.flush() it complained about unsatisfied requests, but adding the flush, just caused an "No pending requests" error.

Extensive use of search engines didn't yield an answer for me, so can you help me?

Was it helpful?

Solution

I suspect no, but you could still unit test your code if you refactor it slightly:

  • Create a small factory that returns a new $window.XMLHttpRequest().

  • Then in the services/controllers, instead of calling new XMLHttpRequest() directly, inject this factory when you need to make call to the upload()

  • You can unit test the service/controllers by mocking up the factory and injecting it in before the test.

  • You can even unit test the small factory by mocking up $window with an XMLHttpRequest constructor, and injecting that in before the test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top