re: 1. let, const and ... var VIEW POST

FULL DISCUSSION
 

var is useful with Jest.

try {
  await foo()
} catch (e) {
  var error = e
}
expect(error.message).toMatch(/foo/)
 

Could you please explain why you use only var with jest?

 

Oh, no. I only ever use var in this scenario. Lets me skip out of the block scope without a separate variable declaration. And if no error happens, the variable is just undefined.

Aha :)
So here is a place where var is still useful 😉

@adrianhelvik
Did you mean:

let error
try {
  await foo()
} catch (e) {
  error = e
}
expect(error.message).toMatch('foo') // you can use string literals if you don't have a complex RegEx
 

Any reason to not put the expect inside the catch bloc ?

 

Yes. If it doesn't throw assertion wouldn't run, and the test would pass.
You'd have to do

expect.assertions(1)
try {
  await foo()
} catch (e) {
  var error = e
  expect(error.message).toMatch(/foo/)
}

Personally, I'd just go with

await expect(foo()).rejects.toThrow('foo')
// Or, if final in the test:
return expect(foo()).rejects.toThrow('foo') // doesn't require `async` `it`

(No need for expect.assertions(1) since the expect runs synchronously inline)

 

Honestly, I would simply:

await expect(foo()).rejects.toThrow(/foo/)

Since foo is an async function, it implicitly returns a promise so you can use the .resolves / .rejects matchers and then use the toThrow method, and this accepts a regex or string to match the error message property. IMHO it reads more semantically correct.

Cheers,

 

The toThrow API is quite weird.
If you pass a string, it matches it anywhere, so 'foo' and /foo/ is the same.
And if you want to strictly match the whole message, you need to do

.toThrow(/^literal message$/) // RegEx with ends
.toThrow(new Error('literal message')) // The Error class does NOT matter in this case.

If you actually care about the constructor, you have to pass just it.

.toThrow(SpecialError)

I use

expect(badFunc).toThrowErrorMatchingInlineSnapshot()

a lot nowadays.

code of conduct - report abuse