function foo() {
throw new Error('an error from (foo)');
}
I want to check if the error contains the text (foo)
, I tried:
expect(() => foo()).toThrow(expect.stringContaining('(foo)'))
But which is failed and does not work as expected:
● test › checks error containing text
expect(received).toThrowError(expected)
Expected asymmetric matcher: StringContaining "(foo)"
Received name: "Error"
Received message: "an error from (foo)"
1 | function foo() {
> 2 | throw new Error('an error from (foo)');
| ^
Although I can find a way with regex like:
expect(() => foo()).toThrowError(/[(]foo[)]/)
But which requires me to escape some special characters, which is not what I want.
Why is expect.stringContaining
not supported in this case? Or do I miss anything?
A small demo for trying:
function foo() {
throw new Error('an error from (foo)');
}
I want to check if the error contains the text (foo)
, I tried:
expect(() => foo()).toThrow(expect.stringContaining('(foo)'))
But which is failed and does not work as expected:
● test › checks error containing text
expect(received).toThrowError(expected)
Expected asymmetric matcher: StringContaining "(foo)"
Received name: "Error"
Received message: "an error from (foo)"
1 | function foo() {
> 2 | throw new Error('an error from (foo)');
| ^
Although I can find a way with regex like:
expect(() => foo()).toThrowError(/[(]foo[)]/)
But which requires me to escape some special characters, which is not what I want.
Why is expect.stringContaining
not supported in this case? Or do I miss anything?
A small demo for trying: https://github./freewind-demos/typescript-jest-expect-throw-error-containing-text-demo
Share Improve this question edited Oct 13, 2020 at 16:01 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Oct 9, 2020 at 7:16 FreewindFreewind 198k163 gold badges452 silver badges733 bronze badges 01 Answer
Reset to default 15toThrow
doesn't accept a matcher. Per the documentation the optional error argument has four options:
You can provide an optional argument to test that a specific error is thrown:
- regular expression: error message matches the pattern
- string: error message includes the substring
- error object: error message is equal to the message property of the object
- error class: error object is instance of class
In your case you can use either:
the regex option
.toThrow(/\(foo\)/)
(you don't need a character class just to escape parentheses) or by running the string through a function to escape it for you (see e.g. Is there a RegExp.escape function in JavaScript?) then passing it to
new RegExp
; orthe string option
.toThrow("(foo)")