Provides a helper to test if Throw occurs in javascript or typescript.
- Zero dependency.
- Fully compatible with TypeScript.
- Supports both ESM (ES Modules) and CommonJS module systems.
- Works with both synchronous and asynchronous functions.
- Supports both functions and class methods, with or without arguments.
- Sample code tested to work with both jest and vitest.
Replace and execute the command according to the package manager you are using. Here is an example of npm.
npm install --save-dev has-throw
Note
Check the test code in the src directory for details of the usage example.
This code is supported by both jest and vitest.
import { hasThrow } from 'has-throw';
test('should return true if function throws', () => {
const fn = () => {
throw new Error();
};
expect(hasThrow(() => fn())).toBeTruthy();
});
test('should return false if function does not throw', () => {
const fn = () => {};
expect(hasThrow(() => fn())).toBeFalsy();
});
const { hasThrow } = require('has-throw');
test('should return true if function throws', () => {
const fn = () => {
throw new Error();
};
expect(hasThrow(() => fn())).toBeTruthy();
});
test('should return false if function does not throw', () => {
const fn = () => {};
expect(hasThrow(() => fn())).toBeFalsy();
});
Important
Promise is truthy and needs to be resolved and strictly checked with toStrictEqual.
This code is supported by both jest and vitest.
import { hasAsyncThrow } from 'has-throw';
test('should return true if function throws', () => {
const fn = async () => {
throw new Error();
};
return expect(hasAsyncThrow(async () => await fn())).resolves.toStrictEqual(true);
});
test('should return false if function does not throw', () => {
const fn = async () => {};
return expect(hasAsyncThrow(async () => await fn())).resolves.toStrictEqual(false);
});
const { hasAsyncThrow } = require('has-throw');
test('should return true if function throws', () => {
const fn = async () => {
throw new Error();
};
return expect(hasAsyncThrow(async () => await fn())).resolves.toStrictEqual(true);
});
test('should return false if function does not throw', () => {
const fn = async () => {};
return expect(hasAsyncThrow(async () => await fn())).resolves.toStrictEqual(false);
});