Is it possible to disable specific React warnings from Jest (using Create React App)

Gas*_*sim 5 reactjs jestjs create-react-app

Recently, React started giving depreciation warnings for componentWillReceiveProps lifecycle method. I am using a library that utilized this function and the maintainers haven't updated their codebase yet.

Currently, any time I run my tests, whether it is in development or in CI, I keep getting ~30 lines of depreciation warnings for each component that the maintainer provides.

Is there a way to suppress these warnings (at least in development)?

EDIT:

I am willing to add certain comments in my files to disable warnings from a specific package if there is a chance:

// some line to disable warnings for this package
import { DateRangePicker } from 'react-dates';
Run Code Online (Sandbox Code Playgroud)

Apr*_*ion 14

如果要禁用满足某些条件的所有警告,并为所有测试保留所有其他警告:

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

React 代码库也包含expect(render(...)).toWarnDev(...),但未包含在Jest 文档中,如果您想使用该功能,您可能需要进行更多调查。


小智 6

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

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

如果你想跨测试做到这一点,你可以这样做:

let consoleSpy;

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

afterAll(() => consoleSpy.mockRestore());
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,当真正的警告发生时,这会导致无限的复活。使用 const originWarn = console.warn.bind(console.warn)`,然后根据@Aprillion 的答案在实现中调用originalWarn。 (2认同)