Mocking ajax
XMLHTTPRequest
. Most newer codebases use either
fetch
or a wrapper library that is more amenable to dependency injection than
XMLHTTPRequest
is. Code using those approaches can be tested
with Jasmine's built-in spy functionality, as described in
the FAQ.
Testing AJAX callsWe have written a plugin called jasmine-ajax
that allows ajax calls to be mocked out in tests. To use it, you need to
download the |
|
Basic Usage Across An Entire Suite |
|
When you want to mock out all ajax calls across an entire suite, use
|
|
Because jasmine-ajax stubs out the global XMLHttpRequest for the page,
you'll want to |
|
Make your requests as normal. Jasmine-Ajax mocks out your request at the XMLHttpRequest object, so should be compatible with other libraries that do ajax requests. |
|
At this point the ajax request won't have returned, so any assertions about intermediate states (like spinners) can be run here. |
|
Now we tell the request what it's response should look like |
|
HTTP response code |
|
You can also specify the content type of the response |
|
responseText to return, this should be a string. |
|
Now that we've told the request to respond, our callback gets called. |
|
You can also specify responses ahead of time and they will respond immediately when the request is made. |
|
Call |
|
Make your requests as normal |
|
If you only want to use it in a single spec, you can use |