14

I am using Karma with mocha to test my React components. I have some warnings displayed when the PropTypes are not matched. However it would be really interesting to have these warnings to cause an actual error, as to track down the test and fix it.

Do you know how this could be achieved?

gcedo
  • 4,811
  • 1
  • 21
  • 28

3 Answers3

19

You can replace the console.warn method with your own and throw when the message provided matches a certain pattern.

let warn = console.warn;
console.warn = function(warning) {
  if (/(Invalid prop|Failed propType)/.test(warning)) {
    throw new Error(warning);
  }
  warn.apply(console, arguments);
};
Alexandre Kirszenberg
  • 35,938
  • 10
  • 88
  • 72
  • 1
    great solution, but had to use `console.error` to get this working with react 0.14 – Spain Train Mar 22 '16 at 23:56
  • 1
    This is good. However because react only warns once it doesn't show every test that would cause the warning, only the first. This means that you get one failing test, you fix it and then the next one fails. It would be great if there was a way to get React to warn every time so every test that causes the warning... Any ideas? – Jack Allan May 06 '16 at 15:37
  • 1
    You could try using `console.error(warning)` instead of throwing an error. – Alexandre Kirszenberg May 06 '16 at 16:14
11

Small improvements to accepted answer: console.error instead of console.warn as spain-train mentioned, added 'Failed prop type' to regex, as only then it works with React 15.3.1, and made the code more strict eslint friendly.

const error = console.error;
console.error = function(warning, ...args) {
  if (/(Invalid prop|Failed prop type)/.test(warning)) {
    throw new Error(warning);
  }
  error.apply(console, [warning, ...args]);
};
Community
  • 1
  • 1
chmurson
  • 619
  • 6
  • 11
0

2021 update:

const consoleError = console.error;

console.error = function (...args) {

  if (/(Invalid prop|Failed propType|Failed .+ type)/.test(args[0])) {

    const errorMessage = args.reduce((p, c) => p.replace(/%s/, c));

    throw new Error(errorMessage);
  }

  consoleError.apply(console, args);
};

Failed prop type is now Failed %s type: %s%s. It uses string substitutions to write to console. Here is the code in React.