Karma and React, have warnings to cause errors

余生颓废 提交于 2019-12-10 02:14:03

问题


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?


回答1:


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);
};



回答2:


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]);
};


来源:https://stackoverflow.com/questions/29651950/karma-and-react-have-warnings-to-cause-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!