【问题标题】:How to create a test for a screen that uses the same hook several times? React Testing Library如何为多次使用相同钩子的屏幕创建测试?反应测试库
【发布时间】:2021-03-13 05:46:57
【问题描述】:

我在 React 中遇到了一个需要挂钩两次的测试场景。在这种情况下,我在同一页面上的两种情况下使用了一个名为 useGet() 的钩子。在我尝试的所有时间中,只有最后一个结果被嘲笑,而第一个结果未定义。有谁知道在同一个测试中模拟两者的方法,以便我可以在测试中呈现完整的 html?

屏幕上使用的需要模拟的变量示例:

const getBoletoCashIn = useGet('all-boletos-cash-in')
const getBoletoCashOut = useGet('all-boletos-cash-out')

try {
  const getCashIn = await getBoletoCashIn.refetch()
  const getCashOut = await getBoletoCashOut.refetch()
  console.log(getCashIn, getCashOut)
} catch(error) {
  console.log(error)
}

测试尝试:

const mockGetData = jest.fn()

jest.mock('@/hooks/useRest', () => {
  return {
    useGet: () => {
      return {
        refetch: mockGetData
      }
    }

  }
})

const customRender = (ui: JSX.Element, { providerProps, ...renderOptions }: { providerProps: { url: { baseUrl: string } } }) => {
  return render(
    <GlobalProvider>
      <GlobalStyles />
      {ui}
    </GlobalProvider>,
    renderOptions
  )
}

describe('Cash-In & Cash-Out chart component', () => {
  it('', async () => {
    const { debug } = customRender(
      <CashInCashOutChart />,
      { providerProps }
    )

    // Array aleatório
    mockGetData.mockImplementationOnce(() => ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
    mockGetData.mockImplementationOnce(() => ([1, 2, 3, 4, 5]))

    await waitFor(() => expect(mockGetData).toHaveBeenCalledTimes(1))

    await waitFor(() => {
      debug()
    })
  })
})

【问题讨论】:

    标签: javascript reactjs jestjs mocking render


    【解决方案1】:

    我通过将 mockImplementationOnce 直接放置在它外部的这段代码中 () 解决了这个问题,并删除了其中的那些,只留下了 toHaveBeenNthCalledWith。

    jest.mock('@/hooks/useRest', () => {
      return {
        useGet: jest.fn((url) => {
          if (url === 'all-boletos-cash-in') {
            return {
              refetch: mockGetData.mockImplementationOnce(() => [1, 2, 3])
            }
          }
          if (url === 'all-boletos-cash-out') {
            return {
              refetch: mockGetData.mockImplementationOnce(() => [1, 2, 3, 4, 5])
            }
          }
        })
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2020-06-01
      相关资源
      最近更新 更多