For development and unit testing you may need to force a promise chain to fail in various ways.
In listing 1 below is shown a simple XHR request. Now to make sure our promise chain error handling is working correctly we want the Ajax call to fail.
One way of achieving this to just change the url of the XHR destination. This is fine here, but is not a generic approach since not every async function or service is based on a URL or even single value.
Another approach is shown in listing 2. Here we cancel the promise. In Dojo’s promise implementation we can cancel(reason,flag) a promise giving a reason and a flag, and even invoke a cancel handler if the promise was created with one. If this flag is true, a successful async call will result in a failure. Unfortunately, unless you type at superhuman speeds, this can’t be added at a debugger breakpoint and must be coded in temporarily.
Listing 1
/** * XHR call. * @returns promise */ function _loadData(requestParams) { var promise; require([ "dojo/request"], function(request) { promise = request.post("someurl", { data : requestParams, handleAs : "json", preventCache : true }) }); return promise; }
Listing 2
function _loadData(requestParams) { var promise; require([ "dojo/request"], function(request) { promise = request.post("someurl", { data : requestParams, handleAs : "json", preventCache : true }) }); promise.cancel("force error",true); return promise; }
There are XUnit type testing frameworks for JavaScript that may be able to do this failure testing better. I have not looked into this yet.
Further reading
- Chaining promises (HTML)
- JavaScript Promises There and back again
- Promises/A+
- Testing Asynchronous Javascript w/ Jasmine 2.0.0