1.0.2 • Published 6 months ago
has-throw v1.0.2
has-throw
Provides a helper to test if Throw occurs in javascript or typescript.
Features
- 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.
Installation
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
Examples
!NOTE Check the test code in the src directory for details of the usage example.
hasThrow
ES modules
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();
});
CommonJS
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();
});
hasAsyncThrow
!IMPORTANT Promise is truthy and needs to be resolved and strictly checked with toStrictEqual.
ES modules
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);
});
CommonJS
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);
});