【问题标题】:Is it possible to disable specific React warnings from Jest (using Create React App)是否可以从 Jest 禁用特定的 React 警告(使用 Create React App)
【发布时间】:2020-01-29 11:21:00
【问题描述】:

最近,React 开始为 componentWillReceiveProps 生命周期方法提供折旧警告。我正在使用一个使用此功能的库,维护人员尚未更新他们的代码库。

目前,每当我运行测试时,无论是在开发中还是在 CI 中,我都会不断收到维护者提供的每个组件的大约 30 行折旧警告。

有没有办法抑制这些警告(至少在开发中)?

编辑:

如果有机会,我愿意在我的文件中添加某些 cmets 以禁用来自特定包的警告:

// some line to disable warnings for this package
import { DateRangePicker } from 'react-dates';

【问题讨论】:

  • 你可以尝试覆盖console.warn
  • 这将删除所有地方的警告。我不认为这是一个好主意。在我的测试文件中覆盖它时,没有任何反应。
  • 您是否尝试过为 Jest 使用 --silent 参数?
  • 标记那些方法 UNSAFE_ 。即你的 componentWillReceiveProps 将变为 UNSAFE_componentWillReceiveProps 。尝试这个。我认为这会让你摆脱那些警告。
  • @Daniele 但这会禁用所有警告。我只需要禁用此警告。或仅针对特定包的警告。

标签: reactjs jestjs create-react-app


【解决方案1】:

如果你想禁用所有满足某些条件的警告,保留所有其他警告,用于所有测试:

const originalWarn = console.warn.bind(console.warn)
beforeAll(() => {
  console.warn = (msg) => 
    !msg.toString().includes('componentWillReceiveProps') && originalWarn(msg)
})
afterAll(() => {
  console.warn = originalWarn
})

React codebase 还包含 expect(render(...)).toWarnDev(...),但 Jest documentation 中不包含它,如果您想使用该功能,可能需要进行更多调查。

【讨论】:

  • 我将提供的代码放在哪里?因为如果我将代码完全复制/粘贴到我的类文件中,它就会出错。
  • @LukeCarelsen 在包含测试的文件中,请参阅Setup and Teardown Jest 文档
【解决方案2】:

在概念上与之前的答案类似,但更简单的是:

jest.spyOn(global.console, 'warn').mockImplementationOnce((message) => {
  if (!message.includes('componentWillReceiveProps')) {
    global.console.warn(message);
  }
});

如果您想跨测试这样做,您可以这样做:

let consoleSpy;

beforeAll(() => {
  consoleSpy = jest.spyOn(global.console, 'warn').mockImplementation((message) => {
    // same implementation as above
});

afterAll(() => consoleSpy.mockRestore());

【讨论】:

  • 对我来说,当真正的警告发生时,这会导致无限的复活。使用const originalWarn = console.warn.bind(console.warn),然后根据@Aprillion 的回答在实现中调用 originalWarn。
【解决方案3】:

所以我找到了一种方法来修复使用 react-codemod 的任何库的这些警告。 由于这个库不能在 node_modules 中工作,所以必须做一些 hack。

运行:

 yarn add -D react-codemod
 open ./node_modules/react-codemod/bin/cli.js
  • 删除/注释行 (72) >
    + // args.push('--ignore-pattern=/node_modules/');

运行:

./node_modules/.bin/react-codemod rename-unsafe-lifecycles

用库的路径回答这个问题,你想修复...

“应该在哪些文件或目录上应用 codemods?”

./node_modules/react-dates/lib/** // 或任何有问题的库

这可能是一个临时修复,直到 react-codemod 支持 node_modules 库。 您还可以分叉库并为自己删除该行,并在您的 CI 管道中像这样使用它,这样就不会再收到任何这样的警告了。

【讨论】:

  • 我强烈建议不要修改 node_modules 中的任何内容。这样做需要检查你的 node_modules 目录,你通常也不应该这样做。分叉库很好,尽管使用 jest.spyOn 忽略消息是一个更好的主意。
猜你喜欢
  • 2018-11-07
  • 2017-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多