-
-
Save domenic/1356609 to your computer and use it in GitHub Desktop.
// Say that doSomethingAsync returns a promise, and expected is the value we want it to return. | |
// With my library you can do the following | |
test("doSomethingAsync() returns expected", function () { | |
equal(doSomethingAsync(), expected, "As expected"); | |
}); | |
// Normally you would have to do | |
test("doSomethingAsync() returns expected", function () { | |
QUnit.stop(); | |
doSomethingAsync().then( | |
function (result) { | |
equal(result, expected, "As expected"); | |
}, | |
function () { | |
ok(false, "Promise broken"); | |
} | |
}).fin(QUnit.start); | |
} | |
// With a slight mashup of @kriskowal's UncommonJS testing spec with QUnit, it would look something like | |
test("doSomethingAsync() returns expected", function () { | |
return doSomethingAsync().then(function (result) { | |
equal(result, expected, "As expected"); | |
}); | |
}); |
…in fact, I already wrote the spec. https://github.com/kriskowal/uncommonjs/blob/master/tests/specification.md
That approach makes sense, and is less error-prone than what I've done. (For example, if you use two of my equal
s it would start and stop the testrunner twice.) Thanks for the pointer to UncommonJS testing; I've seen it around but never spent enough time trying to understand it before now.
One thing I like about my helpers is the automatic failure if the promise is broken. It is very often the case that you are testing the success path. I also have assertBroken
to handle the rest, which has similar semantics to QUnit.raises
(which is a superset of UncommonJS's error
).
I'm still playing around with a robust way to do all this, which is why it's unreleased. I'll update the gist with a comparison to your approach. Thoughts appreciated on other promise test sugar.
Sorry, after reading the spec more carefully I see that there is automatic failure for broken promises there too.
I am thinking of doing something similar with CommonJS testing (Irakli’s “test” in NPM), allowing the test function to return a promise and doing the .stop() and .fin(start) work internally. It’s a common pattern that needs to get swallowed in the library.