首页 > 其他 > 详细

[React Testing] Test componentDidCatch handler Error Boundaries

时间:2020-05-01 20:44:39      阅读:56      评论:0      收藏:0      [点我收藏+]

Error boundary:

import React from react
import { reportError } from ./components/extra/api

export default class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false }
  }

  static defaultProps = {
    fallback: <h1>Something went wrong.</h1>,
  }

  static getDerivedStateFromError(error) {
    return { hasError: true }
  }

  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo)
    reportError(error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback
    }

    return this.props.children
  }
}

 

What we want to test is ‘reportError‘ was called when error happens

Test:

import React from react
import { render, fireEvent } from @testing-library/react
import { ErrorBoundary } from ./error-boundary
import { reportError as mockReportError } from ./components/extra/api

function Bomb(shouldThrow) {
  if (shouldThrow) {
    throw new Error(Bomb)
  } else {
    return null
  }
}

jest.mock(./components/extra/api)

test(calls reportError and renders that there was a problem, () => {
  mockReportError.mockResolvedValueOnce({ success: true })
  const { rerender } = render(
    <ErrorBoundary>
      <Bomb />
    </ErrorBoundary>,
  )

  rerender(
    <ErrorBoundary>
      <Bomb shouldThrow={true} />
    </ErrorBoundary>,
  )

  const error = expect.any(Error)
  const errorInfo = { componentStack: expect.stringContaining(Bomb) }
  expect(mockReportError).toHaveBeenCalledWith(error, errorInfo)
  expect(mockReportError).toHaveBeenCalledTimes(1)
})

// Clearn the mock impl afterEach(()
=> { jest.clearAllMocks() })

 

Notice:

  const error = expect.any(Error)
  const errorInfo = { componentStack: expect.stringContaining(Bomb) }

Both uses ‘expect‘ static methods.

expect.any(): https://jestjs.io/docs/en/expect#expectanyconstructor

expect.stirngContiaining(): https://jestjs.io/docs/en/expect#expectstringcontainingstring

 

In the testin, we mock the whole ‘api‘ module with jest.fn(), just provide the mock implementation for ‘reportError‘:

mockReportError.mockResolvedValueOnce({ success: true })

 

Remember to claer the mock Implmentation after each test:

afterEach(() => {
  jest.clearAllMocks()
})

 

[React Testing] Test componentDidCatch handler Error Boundaries

原文:https://www.cnblogs.com/Answer1215/p/12814559.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!