T
TanStack4y ago
stormy-gold

Jest testing with RQ and ensuring that the query is done before proceeding

Followed the guidance from https://tanstack.com/query/v4/docs/guides/testing (except I'm using @testing-library/react-native and not @testing-library/react-hooks) Say I got a MenuScreen that contains a lot of MenuLink
export function MenuLink({ fallbackScreen = 'OverviewRoot', ...rest }: Props) {
const props = { fallbackScreen, ...rest }
const user = useUser()
export function MenuLink({ fallbackScreen = 'OverviewRoot', ...rest }: Props) {
const props = { fallbackScreen, ...rest }
const user = useUser()
I then had made this TestHelper that allows me to render with a specific user
it(`falls back to the Overview screen when user is NOT created in the bank`, async () => {
const { utils } = await TestHelper.renderWithUserAsync(
<MenuScreen />,
'some-seeded-user@example.com'
)
const menuLink = await utils.findByLabelText('Kontoinformation')
TestHelper.fireEvent(menuLink, 'onPress')
expect(useNavigationMock.navigate).toHaveBeenCalledWith(routeTypeGuard('OverviewRoot'))
})
it(`falls back to the Overview screen when user is NOT created in the bank`, async () => {
const { utils } = await TestHelper.renderWithUserAsync(
<MenuScreen />,
'some-seeded-user@example.com'
)
const menuLink = await utils.findByLabelText('Kontoinformation')
TestHelper.fireEvent(menuLink, 'onPress')
expect(useNavigationMock.navigate).toHaveBeenCalledWith(routeTypeGuard('OverviewRoot'))
})
To ensure that the query is done - before doing any assertions I try to check the testQueryClient
export async function renderWithUserAsync(
Element: JSX.Element,
email: keyof typeof userCredentials,
awaitQueryClient?: boolean
) {
const user = await getSessionAsync(email) // <-- sets the auth cookie - also for the axios instance used in useUser
const { utils } = renderWithProviders(Element)

if (awaitQueryClient === undefined || awaitQueryClient) {
expect(utils.testQueryClient.getQueryData([QUERY_KEY_USER])).toBeUndefined()
await waitFor(() => {
expect(utils.testQueryClient.getQueryData([QUERY_KEY_USER])).toEqual(user)
})
}

return { utils, user }
export async function renderWithUserAsync(
Element: JSX.Element,
email: keyof typeof userCredentials,
awaitQueryClient?: boolean
) {
const user = await getSessionAsync(email) // <-- sets the auth cookie - also for the axios instance used in useUser
const { utils } = renderWithProviders(Element)

if (awaitQueryClient === undefined || awaitQueryClient) {
expect(utils.testQueryClient.getQueryData([QUERY_KEY_USER])).toBeUndefined()
await waitFor(() => {
expect(utils.testQueryClient.getQueryData([QUERY_KEY_USER])).toEqual(user)
})
}

return { utils, user }
But when upgrading to v4 it has revealed that some of my flaky test might be cause by this assumption might not be working - seems not to waiting TestHelper.renderWithUserAsync to be done .
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?