From 091b4d3701ad5957cfaf0283e111557c6a323a6c Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 10 May 2018 19:36:01 -0500 Subject: [PATCH] Add Turn Off Console Error Messages In A Test as a javascript til --- README.md | 3 ++- ...rn-off-console-error-messages-in-a-test.md | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 javascript/turn-off-console-error-messages-in-a-test.md diff --git a/README.md b/README.md index c315fa0..679b460 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_677 TILs and counting..._ +_678 TILs and counting..._ --- @@ -268,6 +268,7 @@ _677 TILs and counting..._ - [Timing Processes](javascript/timing-processes.md) - [Transforming ES6 and JSX With Babel 6](javascript/transforming-es6-and-jsx-with-babel-6.md) - [Truthiness of Integer Arrays](javascript/truthiness-of-integer-arrays.md) +- [Turn Off Console Error Messages In A Test](javascript/turn-off-console-error-messages-in-a-test.md) - [Waiting On Multiple Promises](javascript/waiting-on-multiple-promises.md) - [Who Am I: NPM Edition](javascript/who-am-i-npm-edition.md) - [Yarn Commands Without The Emojis](javascript/yarn-commands-without-the-emojis.md) diff --git a/javascript/turn-off-console-error-messages-in-a-test.md b/javascript/turn-off-console-error-messages-in-a-test.md new file mode 100644 index 0000000..90c4d90 --- /dev/null +++ b/javascript/turn-off-console-error-messages-in-a-test.md @@ -0,0 +1,25 @@ +# Turn Off Console Error Messages In A Test + +I'm using [Jest](https://facebook.github.io/jest/) to test a React component +that requires a prop via +[PropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html). In +one of my tests, I want to test that component when the required prop is +excluded. The side effect of doing this is that my test output gets +cluttered with the PropType warning. + +The thing to do is silence the error message during that test. + +```javascript +it('renders a component without a required prop', () => { + const originalError = console.error; + console.error = jest.fn(); + + // test code here + expect(shallow()).toDoSomething; + + console.error = originalError; +}); +``` + +We can silence `console.error` by temporarily replacing it with a +Jest-mocked function and then putting it back at the end of the test.