expect().toThrow(): support checking properties
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
- Calling the function direclty myself and wrapping with
try...catch(I have to remember to add an explicitfail()if the function doesn't throw, otherwise the test may pass with a false positive). - Using some setup with a spy to catch the exception… not sure if that is a thing yet or not.
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