npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

throw-on

v0.8.0

Published

Throw on console.error() & fetch

Downloads

8,348

Readme

throw-on

npm version Node.js CI Test Coverage Bundle size Prettier Airbnb Code Style

Force console.error/warn and network requests to fail.

  • Tiny: less than 100 lines of code
  • No dependencies
  • Fully tested
  • Written in TypeScript
  • Works with Node.js and browsers
  • Generic: not specific to React or Jest

This is an alternative to https://github.com/ValentinH/jest-fail-on-console

Why?

Do you have warnings like "An update inside a test was not wrapped in act" or "Can't perform a React state update on an unmounted component" when running or testing your React app? Are your tests performing network requests when they shouldn't?

Solution: throw whenever there is a warning (e.g. console.error/warn) or a network request that isn't mocked

  • The sooner a test fails, the easier it is to fix
  • Improve code quality (like an ESLint rule but at run/test time)

throw-on still displays the original console message before throwing an exception with the message throw-on console.[METHOD]: [ORIGINAL_MESSAGE_SHORTEN]

Result:

  • before (test passes)

    before

  • after (test fails)

    after

Usage

In your tests

npm install --save-dev throw-on

// Inside jest.setup.js (Jest setupFilesAfterEnv option) for example

import {
  throwOnConsole,
  throwOnFetch,
  throwOnXMLHttpRequestOpen
} from 'throw-on';

throwOnConsole('assert');
throwOnConsole('error');
throwOnConsole('warn');
throwOnFetch();
throwOnXMLHttpRequestOpen();

In the browser

npm install throw-on

// Inside your entry file (something like index.js, app.js, pages/_app.js)

if (process.env.NODE_ENV !== 'production') { // You probably don't want this in production
  const { throwOnConsole } = await import('throw-on');
  throwOnConsole('assert');
  throwOnConsole('error');
  throwOnConsole('warn');
}

render(<MyApp />, document.getElementById('app'));

Make it your own

Copy-paste throwOnConsole.ts and/or throwOnFetch.ts and/or throwOnXMLHttpRequestOpen.ts into your source code.

Platform support

Tested with Node.js >= 14, might work with Node.js 12.

Transpilation to ES5 (via Babel for example) is needed for non-modern browsers.

API

type Options = {
  /**
   * Messages to ignore (won't throw), each message to ignore can be a substring or a regex.
   *
   * Empty list by default.
   */
  ignore?: (string | RegExp)[];
};

type ConsoleMethodName = 'assert' | 'error' | 'warn' | 'info' | 'log' | 'dir' | 'debug';

/**
 * Makes console method to throw if called.
 */
function throwOnConsole(methodName: ConsoleMethodName, options: Options = {}): void;

/**
 * Restores the original console method implementation.
 */
function restoreConsole(methodName: ConsoleMethodName): void;

/**
 * Makes fetch to throw if called.
 */
function throwOnFetch(): void;

/**
 * Restores the original fetch implementation.
 */
function restoreFetch(): void;

/**
 * Makes XMLHttpRequest.open to throw if called.
 */
function throwOnXMLHttpRequestOpen(): void;

/**
 * Restores the original XMLHttpRequest.open implementation.
 */
function restoreXMLHttpRequestOpen(): void;

What about valid console messages?

If a console.error() is expected, then you should assert for it:

test('should log an error', () => {
  const spy = jest.spyOn(console, 'error').mockImplementation();

  // ...

  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy).toHaveBeenCalledWith('your error message');

  spy.mockRestore();
});

Limitations

  • Be careful: it adds a line to Jest stack trace, messing up the codeframe:

    at console.<computed> (src/throwOnConsole.ts:69:7) <===
    at console.error (node_modules/@testing-library/react-hooks/lib/core/console.js:19:7)
    at printWarning (node_modules/react-dom/cjs/react-dom.development.js:67:30)
    at error (node_modules/react-dom/cjs/react-dom.development.js:43:5)
    ...

    Use restoreConsole() to get the original codeframe

  • Be careful: the shorten exception message does not always match the original console message (because of React error boundary?)

  • Libraries that console.* exceptions 1 2 introduce an infinite loop: throw-on intercepts the console.* call and throws an exception => the library catches the exception and console.* it, ect.