Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma and React, have warnings to cause errors

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?

like image 415
gcedo Avatar asked Apr 15 '15 13:04

gcedo


2 Answers

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);
};
like image 180
Alexandre Kirszenberg Avatar answered Nov 20 '22 20:11

Alexandre Kirszenberg


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]);
};
like image 21
chmurson Avatar answered Nov 20 '22 18:11

chmurson