Testing Mutations with Relay in Frontend
Tags: testing, frontend, typescript, tutorial
Published: 2023-04-25 16:38:44

Mocking mutations in your test is the best way to test the behavior of your components after doing some mutation operation, with this we can check if an operation performed successfully as expected.

Mutation is every operation that inserts, updates or deletes data on our server. So we need to test if after deleting something it will be removed from the screen, same for inserts.

Imagine we have a page that render a user and a button to delete this user from your database. Ee start from the principle that you already have the user query and the mutation to remove created. Let's just focus on the tests.

Install the required packages:
```bash
yarn add relay-test-utils
```

First, create a simple test rendering the user from UserQuery, and check if the username is rendered on the screen.

```tsx
import {
  fireEvent,
  render,
  screen,
  waitFor,
  act,
} from "@testing-library/react";
import { createMockEnvironment, MockPayloadGenerator } from "relay-test-utils";
import { RelayEnvironmentProvider } from "react-relay";

import Component from "../Component.tsx";

it("should remove a user", async () => {
  const user = { id: "1", name: "Vinicius" };

  const environment = createMockEnvironment();

  render(
    <RelayEnvironmentProvider environment={environment}>
      <Component />
    </RelayEnvironmentProvider>
  );

  const customMockResolvers = {
    Query: () => ({
      User: user,
    }),
  };

  act(() => {
    environment.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, customMockResolvers)
    );
  });

  expect(screen.getByText("Vinicius")).toBeInTheDocument();
})
```

Find the delete button on screen and fire a click. I will search by `data-testid` attribute.
```tsx
it("should remove a user", async () => {
  
  ...

  const deleteButton = await screen.findByTestId("delete-button");
  fireEvent.click(deleteButton);
});
```

Now create the mutation variables and assert the data between the most recent mutation and the expected mutation. After that, mock the mutation using the `relay-test-utils` package.
```tsx
it("should remove a user", async () => {

  ...

  const variables = {
    input: {
      userId: "1",
    },
  };

  const mutationOperation = environment.mock.getMostRecentOperation();

  const operationVariables = mutationOperation.fragment.variables;

  expect(operationVariables).toEqual(variables);

  const mutationMockResolvers = {
    Mutation: () => ({
      RemoveUser: {
        error: null,
        success: "User removed successfully",
      },
    }),
  };

  act(() => {
    environment.mock.resolveMostRecentOperation((operation) =>
      MockPayloadGenerator.generate(operation, mutationMockResolvers)
    );
  });

  expect(screen.queryByText("Vinicius")).not.toBeInTheDocument();
});
```

Finnaly, check if the user was removed from the screen.
```tsx
it("should remove a user", async () => {

  ...

  expect(screen.queryByText("Vinicius")).not.toBeInTheDocument();
});
```
---

Woovi is a Startup that enables shoppers to pay as they please. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

---

Photo by <a href="https://unsplash.com/@s_midili?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">serjan midili</a> on <a href="https://unsplash.com/photos/2ywxD4TFxzc?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>