Enzyme/Jest 测试 useEffect()

Enzyme/Jest test for useEffect()

我有一个看起来像这样的组件:

const PersonalGreeting = (): ReactElement => {
  const [date, setDate] = useState(new Date())
  useEffect(() => {
    const timer = setInterval(() => {
      setDate(new Date())
    }, 60000)

    return () => {
      clearInterval(timer)
    }
  }, [])

  return (
    <div>{date}></div>
  )
}

我遇到了一个错误,指出 Jest: "global" coverage threshold for functions (89%) not met: 88.73%,当我查看日志时,它明确指出我的 return ()useEffect() 中的 clearInterval(timer) 没有被测试。这是一个截图:

老实说,我正在绞尽脑汁想弄清楚他们想让我测试什么。这是我测试过的:

describe('PersonalGreeting', () => {
  const setTimeOfDay = jest.fn()
  // eslint-disable-next-line
  const useToggleMock: any = (initialState: string) => [
    initialState,
    setTimeOfDay
  ]

  beforeEach(() => {
    jest.spyOn(React, 'useState').mockImplementation(useToggleMock)
  })

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

  it('renders component as expected', () => {
    const wrapper = mount(
      <TestWrapper>
        <PersonalGreeting />
      </TestWrapper>
    )

    expect(wrapper.text().length > 0).toBe(true)
  })

  it('Checks time every minute', () => {
    jest.useFakeTimers()
    mount(
      <TestWrapper>
        <PersonalGreeting />
      </TestWrapper>
    )

    expect(setTimeOfDay).not.toBeCalled()

    // 1 minute
    jest.advanceTimersByTime(60000)
    expect(setTimeOfDay).toHaveBeenCalledTimes(1)
  })
})

您需要卸载组件,这将触发 useEffect()

中的 return 函数

docs

像这样


it('Should unmount component', () => {
  const wrapper = mount(
    <TestWrapper>
      <PersonalGreeting />
    </TestWrapper>
  )

  wrapper.unmount();
  // continue with your expect here

})