Skip to content

Instantly share code, notes, and snippets.

@thurt
Forked from jsdf/setupTestFramework.js
Last active October 3, 2017 20:48
Show Gist options
  • Save thurt/a7651202eef97d25bee1c12f81b796f7 to your computer and use it in GitHub Desktop.
Save thurt/a7651202eef97d25bee1c12f81b796f7 to your computer and use it in GitHub Desktop.
Make React PropType warnings throw errors in Jasmine/Jest
/* global jasmine */
/* eslint-disable no-console */
// this file is a modified version of https://gist.github.com/jsdf/6fc35890e4ed4a219072
import util from 'util'; // this is a node module
/**
* This file is called by Jest when running tests
* It elevates React PropType console warnings to exceptions.
* This can be helpful because it will prevent tests from passing if PropTypes
* for the component are not valid.
* Additionally, this enables you to use Jest's expect().toThrowError() or expect().not.toThrowError()
* against component invocations
*/
// keep a reference to the original console methods
const consoleWarn = console.warn;
const consoleError = console.error;
const elevateLogToError = (...args) => {
throw new Error(util.format.apply(this, args).replace(/^Error: (?:Warning: )?/, ''));
};
jasmine.getEnv().beforeEach(() => {
// make calls to console.warn and console.error throw an error
console.warn = elevateLogToError;
console.error = elevateLogToError;
});
jasmine.getEnv().afterEach(() => {
// return console.warn and console.error to default behaviour
console.warn = consoleWarn;
console.error = consoleError;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment