eslint-plugin-ava
eslint-plugin-ava copied to clipboard
Rule proposal: `prefer-t-throws`
I was reviewing some codes using ava and found this pattern repeating often:
try {
await request(requestOptions);
} catch (error) {
t.true(error.statusCode === 500);
}
This can be written instead as:
const error = await t.throws(request(requestOptions));
t.true(error.statusCode === 500);
I think the latter should be preferred.
IssueHunt Summary
Backers (Total: $80.00)
issuehunt ($80.00)
Submitted pull Requests
Become a backer now!
Or submit a pull request to get the deposits!
Tips
- Checkout the Issuehunt explorer to discover more funded issues.
- Need some help from other developers? Add your repositories on IssueHunt to raise funds.
Sounds like a good idea to me :+1:. Not sure when/why try/catch makes sense in tests when t.throws is available.
The second example is better, but FYI, using t.fail() would improve your first example.
try {
await request(requestOptions);
t.fail();
} catch (error) {
t.true(error.statusCode === 500);
}
The second example is better, but FYI, using t.fail() would improve your first example.
Another idea for a lint rule. :-)
👍 Sounds good. PR welcome :)
I think prefer-t-throws would be a better name. We don't want to prevent all usage of try/catch. Thoughts?
Agreed
I think prefer-t-throws would be a better name. We don't want to prevent all usage of try/catch. Thoughts?
What would be a valid use case for try..catch that cannot translate to t.throws?
I think that t.throws() handles every case you'd use a try catch for, and even the Promise#catch() case.
@gajus Maybe something that might throw, but that you don't care about in the test, so you'd like to silence it. I'm sure there are other cases we can't think of too. But the main point is that the intent is clearer with prefer-t-throws than no-try-catch; We want to recommend using t.throws(), not arbitrarily prevent try/catch.
The immediate valid use case for try..catch that came up in my mind is error handling in Koa:
app.use(function * (next) {
try {
yield* next;
} catch (err) {
// handle error
}
});
We don't want to prevent all usage of try/catch.
Definitely agree with this.
@issuehunt has funded $80.00 to this issue.
- Submit pull request via IssueHunt to receive this reward.
- Want to contribute? Chip in to this issue via IssueHunt.
- Checkout the IssueHunt Issue Explorer to see more funded issues.
- Need help from developers? Add your repository on IssueHunt to raise funds.