diff --git a/docs/assert/rejects.md b/docs/assert/rejects.md index e0e0cff4f..1ea4bd945 100644 --- a/docs/assert/rejects.md +++ b/docs/assert/rejects.md @@ -90,3 +90,32 @@ QUnit.test( "rejects example", assert => { ); }); ``` + +The `assert.rejects()` method returns a `Promise` which handles the (often asynchronous) resolution and rejection logic for test successes and failures. It is not required to `await` the returned value, since QUnit internally handles the async control for you and waits for a settled state. However, if your test code requires a consistent and more isolated state between `rejects` calls, then this should be explicitly awaited to hold back the next statements. + +```js +QUnit.test( "stateful rejects example", async assert => { + let value; + + // asynchronously resolve if value < 5, and reject otherwise + function asyncChecker() { + return new Promise((resolve, reject) => { + setTimeout(() => { + if (value < 5) { + resolve(); + } else { + reject("bad value: " + value); + } + }, 10) + }); + } + + value = 8; + await assert.rejects( asyncChecker(), /bad value: 8/ ); + + // if the above was not awaited, then the next line would change the value + // before the previous assertion could occur, and would cause a test failure + value = Infinity; + await assert.rejects( asyncChecker(), /bad value: Infinity/ ); +}); +``` diff --git a/test/main/assert.js b/test/main/assert.js index afab117de..c8ce12201 100644 --- a/test/main/assert.js +++ b/test/main/assert.js @@ -483,6 +483,13 @@ QUnit.test( "rejects", function( assert ) { buildMockPromise( undefined ), "reject with undefined against no matcher" ); + + // should return a thenable + var returnValue = assert.rejects( + buildMockPromise( undefined ) + ); + assert.strictEqual( typeof returnValue, "object" ); + assert.strictEqual( typeof returnValue.then, "function" ); } ); QUnit.module( "failing assertions", {