samedi 17 avril 2021

Testing Apollo - one query with multiple results

I'm trying to test all possible values for a custom hook I did, based on the result of a query.

To do that, I'm using MockedProvider from Apollo client. The problem is because I can't find an easy way to mock different responses not copy-pasting multiple MockedProvider with different mocked data.

import React, { ReactElement, FunctionComponent } from 'react';
import { MockedProvider } from '@apollo/client/testing';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { renderHook } from '@testing-library/react-hooks';
import { QUERY_BANNER } from '../queries';
import { contentBanner } from '../types';
import { useBannerProfile, images } from '../use-banner-profile';
const mocks = [
  {
    request: {
      query: QUERY_BANNER,
    },
    result: {
      data: {
        stateBanner: {
          type: 'contacts',
          __typename: 'StateBanner',
        },
      },
    },
  },
];
const Stack = createStackNavigator();
const MockedNavigator: FunctionComponent = ({ children }) => {
  const MockedScreen = (): ReactElement => <>{children}</>;
  return (
    <MockedProvider mocks={mocks}>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="MockedScreen" component={MockedScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </MockedProvider>
  );
};
test('title and image for contacts banner', async () => {
  const { result, wait } = renderHook(() => useBannerProfile(), {
    wrapper: MockedNavigator,
  });
  await wait(
    () =>
      result.current.title !== contentBanner.default.title &&
      result.current.backgroundImage !== contentBanner.default.backgroundImage,
  );
  expect(result.current.title).toBe(contentBanner.contacts.title);
  expect(result.current.backgroundImage).toBe(images.contacts);
});

Is there any way to change only the result, for instance:

stateBanner: {
  type: 'other-type',
  __typename: 'StateBanner',
},

I was looking documentation from Apollo and from React Hooks Testing Library, but I couldn't find an answer.

Thanks!

Aucun commentaire:

Enregistrer un commentaire