Skip to content

Provides a helper to test if Throw occurs in javascript or typescript.

License

Notifications You must be signed in to change notification settings

huuyafwww/has-throw

Repository files navigation

has-throw

MIT License

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);
});

License

MIT

About

Provides a helper to test if Throw occurs in javascript or typescript.

Resources

License

Stars

Watchers

Forks

Packages

No packages published