Asserts that an error of the given class - or one of its subclasses - is thrown.
The expected error class - also matched if one of its subclasses is thrown.
Optional
predicate: (error: E) => booleanIf specified, this predicate about the error must be true
for the matcher to pass; if the error class is not matched, the predicate is just ignored.
class TestError extends Error {
constructor(readonly magicNumber: number) {
super();
}
}
class AnotherError extends Error {}
expect(() => {
throw new TestError(90);
}).toThrowClass(TestError);
expect(() => {
throw new TestError(90);
}).not.toThrowClass(AnotherError);
The matcher can also take a second parameter - a predicate evaluating the error:
class TestError extends Error {
constructor(readonly magicNumber: number) {
super();
}
}
expect(() => {
throw new TestError(90);
}).toThrowClass(TestError, error => error.magicNumber == 90)
expect(() => {
throw new TestError(90);
}).not.toThrowClass(TestError, error => error.magicNumber == 7)
Subclasses equally satisfy the matcher:
class TestError extends Error {
constructor(readonly magicNumber: number) {
super();
}
}
class SubError extends TestError {}
expect(() => {
throw new SubError(92);
}).toThrowClass(TestError)
expect(() => {
throw new SubError(92);
}).toThrowClass(TestError, error => error.magicNumber == 92)
Gallery of vanilla matchers - compatible with any language implementation supported by Vitest.
To install them at runtime, you'll need this reference in Vitest's configuration file:
To access them via TypeScript, just add this line to some global
.d.ts
file included by tsconfig.json: