Skip to content

assertThrows and assertRejects: check properties of the thrown error other than message #6592

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lionel-rowe opened this issue Apr 16, 2025 · 2 comments

Comments

@lionel-rowe
Copy link
Contributor

lionel-rowe commented Apr 16, 2025

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

For example, DOMExceptions with standardized name prop (but no standardized message prop):

// callback form `(err: E) => boolean`
assertRejects(() => new Promise((_, rej) => {
    const s = AbortSignal.timeout(0)
    s.onabort = () => rej(s.reason)
}), DOMException, (x) => x.name === 'TimeoutError')

Or custom error classes that don't use message:

class CustomError extends Error {
    readonly code: number
    constructor(code: number) {
        super()
        this.code = code
    }
}

// property bag form `{ [K in keyof E]: E[K] }`
assertThrows(() => {
    throw new CustomError(-1)
}, CustomError, { code: -1 })

Describe the solution you'd like

Allow checking properties of the thrown error other than message, e.g. with an optional errorCheck parameter.

Describe alternatives you've considered

  • How does this argument fit into the current (overloaded) function signatures?
  • Which form is better — callback, property bag, both, something else?
    • Callback is significantly more customizable (e.g. arbitrary checking of nested properties, more sophisticated checking of message prop such as exact match or regex match)
    • If supporting property bag, would need to decide how to check equality of nested data, possibly requiring an added dependency on assert/equal
@lionel-rowe
Copy link
Contributor Author

I guess this would also needed to be added to assertIsError, so the param would be string | RegExp | ((err: E) => boolean) (and/or { [K in keyof E]: E[K] }).

@kt3k
Copy link
Member

kt3k commented May 15, 2025

As discussed in #6629 (comment), the structure below is recommended way for doing additional assertions:

const e0 = assertThrows(...);
// do assertions about e0
const e1 = await assertRejects(...);
// do assertions about e1

@kt3k kt3k closed this as not planned Won't fix, can't repro, duplicate, stale May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants