码迷,mamicode.com
首页 > 其他好文 > 详细

[React Testing] Test componentDidCatch handler Error Boundaries

时间:2020-05-01 20:33:28      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:doc   call   nta   value   cal   mod   ocs   notice   stat   

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

标签:doc   call   nta   value   cal   mod   ocs   notice   stat   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!