deno_std icon indicating copy to clipboard operation
deno_std copied to clipboard

expect().toThrow(): support checking properties

Open mfulton26 opened this issue 3 months ago • 1 comments

Is your feature request related to a problem? Please describe.

I can check that something will throw but I don't see a straightforward way to check properties on the thrown exception.

Describe the solution you'd like

expect(someFn).toThrow(new Error("kaboom", { cause: new TypeError("bad input") }));

or some way to pass in a function to toThrow() or to get the thrown exception to check things:

expect(someFn).toThrow(new Error("kaboom"), (e) => {
  // more assertions, e.g. on `e.cause`
});
const thrownError = expect(someFn).toThrow(new Error("kaboom"));
// more assertions, e.g. on `thrownError.cause`

Describe alternatives you've considered

  1. Calling the function direclty myself and wrapping with try...catch (I have to remember to add an explicit fail() if the function doesn't throw, otherwise the test may pass with a false positive).
  2. Using some setup with a spy to catch the exception… not sure if that is a thing yet or not.

mfulton26 avatar Aug 26 '25 21:08 mfulton26

I think it might not be implemented, because iirc the expect namespace is supposed to be jest compliant

However it's actually possible to extend the capabilities of expect with custom matchers already I spinned around an alternate version of toThrow() that supports checking both the Error class and the message here (because the std one was only allowing one of them to be checked at once): https://github.com/lowlighter/libs/blob/025b0ea84e6510ecdea76074d09290daf9037138/testing/expect.ts#L350-L381

Maybe you can use something similar for your use-case

lowlighter avatar Aug 28 '25 03:08 lowlighter