jestjs / jestjs/jest

toThrow should return the error

Open
#8,698 24 comments 23 reactions 0 assignees View on GitHub
:rocket: Feature Request
Dominant language
TypeScript
Stars
45.5k
Forks
6.7k
Avg merge
17h 22m
Merged PRs (30d)
24

Description

## 🚀 Feature Proposal

`.toThrow` and `.rejects.toThrow` should return the error thrown.

## Motivation

When working with a project that uses ava I noticed their [`.throws`](https://github.com/avajs/ava/blob/master/docs/03-assertions.md#throwsfn-expected-message) and [`.throwsAsync`](https://github.com/avajs/ava/blob/master/docs/03-assertions.md#throwsasyncthrower-expected-message) return the original error. It is very convenient.

This would make it possible to never need the [`expect.hasAssertions()` + `try / catch`](https://github.com/jest-community/eslint-plugin-jest/issues/295#issuecomment-509974545) syntax.

## Example

```js
function throwSyncError() {
const syncError = new Error('sync error');
syncError.code = 'SYNC';
throw syncError;
}

async function throwAsyncError() {
const asyncError = new Error('sync error');
asyncError.code = 'ASYNC';
throw asyncError;
}

test('can get error message', async () => {
const syncError = expect(() => throwSyncError()).toThrow('sync error');
expect(syncError.code).toEqual('SYNC');

const asyncError = await expect(throwAsyncError()).rejects.toThrow('sync error');
expect(asyncError.code).toEqual('ASYNC');
});
```

## Pitch

Because using `.toThrow` and `.rejects.toThrow` over `try/catch` it prevents tests that don't fail because they no longer reject. https://github.com/facebook/jest/issues/3917

Contributor guide

Open the contributing guide

Research direction

Start by locating Jest's synchronous `.toThrow` and promise `.rejects.toThrow` matcher entry points and their tests. Use the proposal's sync and async examples to understand the expected returned values, including the custom `code` property. Done means both matchers return the original thrown errors while preserving their existing assertion behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
testing-qa
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.