How to create a test for a screen that uses the same hook multiple times? React Testing Library

Asked

Viewed 37 times

1

I came across a test scenario in React where I need to hook twice. In this case I am using a hook called useGet() in two situations on the same page. Of all the times I have tried only the last result is mocked, leaving the first Undefined. Does anyone know a way to mock both in the same test for me to render the full html in the test?

Example of screen variables that need to be mocked:

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)
}

Trial run

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()
    })
  })
})

1 answer

1

I solved by putting the mockImplementationOnce directly on this block of code that was outside the it() and removed those inside the it, leaving only the 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])
        }
      }
    })
  }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.