DEV Community

Discussion on: 1. let, const and ... var

Collapse
 
cms profile image
Christian C. Salvadó

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,

Collapse
 
qm3ster profile image
Mihail Malo

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.