avajs/eslint-plugin-ava

Do you want to work on this issue?

You can request for a bounty in order to promote it!

Rule proposal: `prefer-t-throws` #156

gajus posted onGitHub

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.


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);
}
posted by jfmengels over 8 years ago

The second example is better, but FYI, using t.fail() would improve your first example.

Another idea for a lint rule. :-)

posted by gajus over 8 years ago

👍 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?

posted by sindresorhus over 8 years ago

Agreed

posted by jfmengels over 8 years ago

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?

posted by gajus over 8 years ago

I think that t.throws() handles every case you'd use a try catch for, and even the Promise#catch() case.

posted by jfmengels over 8 years ago

@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.

posted by sindresorhus over 8 years ago

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
  }  
});
posted by vadimdemedes over 8 years ago

We don't want to prevent all usage of try/catch.

Definitely agree with this.

posted by vadimdemedes over 8 years ago

@issuehunt has funded $80.00 to this issue.


posted by IssueHuntBot almost 6 years ago

Fund this Issue

$80.00
Funded
Only logged in users can fund an issue

Pull requests

Recent activities

mesteery submitted an output to  avajs/ eslint-plugin-ava# 156
about 3 years ago
issuehunt funded 80.00 for avajs/eslint-plugin-ava# 156
almost 6 years ago