Skip to content

Instantly share code, notes, and snippets.

@domenic
Created November 10, 2011 23:26
Show Gist options
  • Save domenic/1356609 to your computer and use it in GitHub Desktop.
Save domenic/1356609 to your computer and use it in GitHub Desktop.
Sample of upcoming promise assertions module
// 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");
});
});
@kriskowal
Copy link

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.

@kriskowal
Copy link

@domenic
Copy link
Author

domenic commented Nov 11, 2011

That approach makes sense, and is less error-prone than what I've done. (For example, if you use two of my equals 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.

@domenic
Copy link
Author

domenic commented Nov 11, 2011

Sorry, after reading the spec more carefully I see that there is automatic failure for broken promises there too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment