-
-
Save thurt/a7651202eef97d25bee1c12f81b796f7 to your computer and use it in GitHub Desktop.
Make React PropType warnings throw errors in Jasmine/Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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