How to test React PropTypes through Jest?

前端 未结 6 1175
终归单人心
终归单人心 2020-12-25 12:22

I\'m writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I\'m using npm to install reac

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 12:55

    For unit tests based on Jest, using this on your setup.js will fail any test where console.error (prop-type errors) or console.warn (React compat issues, like still using componentWillUpdate) ends up being called:

    beforeEach(() => {
      jest.spyOn(console, 'error')
      jest.spyOn(console, 'warn')
    })
    
    afterEach(() => {
      /* eslint-disable no-console,jest/no-standalone-expect */
      expect(console.error).not.toBeCalled()
      expect(console.warn).not.toBeCalled()
    })
    

    This breaks when any test calls jest.restoreAllMocks() - for us, calling jest.clearAllMocks()` instead helped.

    It also requires your app to not call console.error or console.warn for "error handling" (scare quotes, since that's usually not a good idea).

提交回复
热议问题