4
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,030
  • 21
  • 100
  • 124
Freewind
  • 185,914
  • 150
  • 408
  • 676

1 Answers1

7

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)")
    
Sarun UK
  • 5,166
  • 6
  • 21
  • 43
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376