chai-expect-rejects
v0.0.1
Published
Assert async exceptions the same way Chai asserts synchronous throws.
Maintainers
Readme
chai-expect-rejects
Assert async exceptions the same way Chai asserts synchronous throws.
Usage
await expectRejects(() => theAsyncFuncYouWantToTest());Why?
Chai already provides a nice way to assert synchronous exceptions:
expect(() => fn()).to.throw();For asynchronous functions, the experience is different.
With chai-as-promised, you usually write:
await expect(fn()).to.be.rejected;Notice the inconsistency:
- Sync: pass a callback (
() => fn()) - Async: pass the promise itself (
fn())
chai-expect-rejects keeps the callback style for async assertions too:
await expectRejects(() => fn());Now synchronous and asynchronous exception assertions follow the same style.
Less Pain When Implementations Change
Tests often care about what happens, not whether an implementation uses a Promise or throws synchronously.
Imagine you start with an async implementation:
async function justWantToThrow() {
throw new Error();
}Your test:
await expectRejects(() => justWantToThrow());Later, the implementation becomes synchronous:
function justWantToThrow() {
throw new Error();
}(or even if you accidentally forget it's no longer async)
The test remains unchanged:
await expectRejects(() => justWantToThrow());This is NOT an encouragement to use expectRejects for synchronous code.
It's simply a nice property that your tests remain valid if an implementation changes from async to sync.
