Skip to content

Support function in message expectation in t.throws / t.throwsAsync #2978

@sindresorhus

Description

@sindresorhus

The most common way to use t.throws is to match against the error message. However, sometimes part of the error message varies by Node.js versions or operating systems. Currently, you would use regex matching for this. But with regex, you have to be careful to escape special symbols.

I suggest adding support for a function as the message. This would make it easy to:

  • Check is a message contains a certain string
  • Check if the error message is one of multiple messages

Examples:

await t.throwsAsync(async () => {
	throw new TypeError('🦄');
}, {
	message: message => ['🦄', '🐴'].includes(message)
});

await t.throwsAsync(async () => {
	throw new TypeError(`${process.platform} is not supported`);
}, {
	message: message => message.includes('is not supported')
});

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions