9
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.com/freewind-demos/typescript-jest-expect-throw-error-containing-text-demo

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

12

toThrow 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; or

  • the string option

     .toThrow("(foo)")
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437