javascript - AngularJs: automatic unit tests for unhandled promises -
assuming have function calls 2 dependend async functions
function targetfn() { asyncfn1(); asyncfn2(); }
this defect, since asyncfn2
not wait asyncfn1
completed. correct implementation be:
function targetfn() { asyncfn1().then(asyncfn2); }
however, how test this? maybe test this:
it("ensures ordering", function() { spyon(window, "asyncfn1").and.callfake(function() { return $q.reject("irrelevant"); }); spyon(window, "asyncfn2"); $timeout.flush(); expect(asyncfn2).not.tohavebeencalled(); });
this okay simple test case. if have several chained async functions? test effort grow exponential; have test every possible combination of rejection , resolving every promise. if change sync function async function afterwards? introduce defect behavior in every callee function without failing tests.
what want automatic detection of unhandled promises. going first example:
function targetfn() { asyncfn1(); asyncfn2(); }
the test system should recognizes asyncfn1
, asyncfn2
creating new promises, there no then
, catch
handler. second example should of course fail:
function targetfn() { asyncfn1().then(asyncfn2); }
because then
introduces new promise not handled, since not returned.
i write test like:
it("does not introduce unhandled promises", function() { expect(targetfn).doesnotintroduceunhandledpromises(); });
and checks if every promise created during execution of targetfn
has either "endpoint" finally
or chained promises returned targetfn
.
do have idea how achive this? or better solution this?
thanks
timo
this defect, since asyncfn2 not wait asyncfn1 completed. correct implementation be:
no it's not, it's pretty common want perform 2 operations in parallel, or downright ignore one's result:
function loadnewdata() { reportdataloadedtogoogleanalytics(); return dataservice.loadnewdata("someparameter"); }
your issue though, promises aren't being returned. rule of thumb whenever method performs async promises, should return promise. eliminate problem of testing interesting promises (return them in mocha)
what want automatic detection of unhandled promises.
that's quite possible, can either use powerful library bluebird , swap out $q
, use built in facilities or decorate $q yourself. when tried these decorations ended hacky begged satan take soul (had new error().stack , grep function name).
Comments
Post a Comment