apollographql / apollo-link-rest

Use existing REST endpoints with GraphQL
MIT License
790 stars 122 forks source link

Apollo Link Rest - MockProvider #303

Open JayYoungman opened 1 year ago

JayYoungman commented 1 year ago

Hey

Im trying to Mock an API request following the Apollo docs for MockProvider, for some reason jest dom is returning a "?", nothing inside my mockQuery is firing it seems, even the error is not being displayed. Any console logs also don't get rendered.

Does MockProvider even work with rest link? Any help would be much appreciated. Some example code below if it helps

export const currentUserFragment: DocumentNode = gql`
  fragment UserFields on User {
    avatar: _avatar
    name
  }
`;
const queryMocks = [
  {
    error: new Error("something went wrong"),
    request: {
      query: query(currentUserFragment),
      variables: {
        id: "1",
      },
    },
    result: {
      data: {
        user: {
          avatar: {
            url: "image.jpg",
          },
          id: "1",
          name: "Jay Youngman",
        },
      },
    },
  },
];

const renderWithContext = (
  overrideContextValue: Partial<GlobalContextValue> = {},
  overrideProps: Partial<HeaderProps> = {}
) =>
  render(
    <GlobalContext.Provider
      value={{ ...globalContextMockValue, ...overrideContextValue }}
    >
      <MockedProvider addTypename={false} mocks={queryMocks}>
        <Header {...defaultProps} {...overrideProps} />
      </MockedProvider>
    </GlobalContext.Provider>
  );

it("displays the users name", async () => {
    renderWithContext();

    await wait(0);

    const userName = screen.getByText("Jay Youngman");
    screen.debug();
    expect(userName).toBeInTheDocument();
  });

Query

  gql`
    query UseCurrentUserQuery($id: ID) {
      user(id: $id) @rest(path: "/users/{args.id}", type: "User") {
        ...UserFields
        id
      }
    }
    ${fragment}
  `;

Thanks

/label Question

fbartho commented 1 year ago

ApolloLinkRest is not necessarily compatible with MockProvider -- I haven't spent any time with that.

If you're trying to add mocking to mock your REST server out, instead you can use one of the fetch-based mocking libraries.

Our unit tests demonstrate how to use fetchMock: https://github.com/apollographql/apollo-link-rest/blob/5e30e2a0d1e1c71d5ab4f4a66407209716f0307f/src/__tests__/restLink.ts#L66 (as an example).