vendredi 27 novembre 2020

How testing my API calls in differents groups of test?

Im starting with react-testing-library, and Im trying to test API calls. I have two sets, one for success request and another for error request.

import React from "react";
import { render, waitForElementToBeRemoved } from "@testing-library/react";
import user from "@testing-library/user-event";
import App from "./App";
import { getUser } from "./serviceGithub";

jest.mock("./serviceGithub");

//Mock data for success and error, Im using the github api
const dataSuccess = {
    id: "2231231",
    name: "enzouu",
};

const dataError = {
    message: "not found",
};

const renderInit = () => {
    const utils = render(<App />);
    const inputUser = utils.getByPlaceholderText("ingrese usuario", {
        exact: false,
    });
    const buttonSearch = utils.getByRole("button", { name: /buscar/i });

    return { utils, buttonSearch, inputUser };
};

test("should success request to api", async () => {
    getUser.mockResolvedValue([dataSuccess]);
    const { utils, buttonSearch, inputUser } = renderInit();
    expect(utils.getByText(/esperando/i)).toBeInTheDocument();
    expect(buttonSearch).toBeDisabled();
    user.type(inputUser, "enzzoperez");
    expect(buttonSearch).toBeEnabled();
    user.click(buttonSearch);
    await waitForElementToBeRemoved(() =>
        utils.getByText("cargando", { exact: false })
    );
    expect(getUser).toHaveBeenCalledWith("enzzoperez");
    expect(getUser).toHaveBeenCalledTimes(1);
    expect(utils.getByText("enzouu", { exact: false })).toBeInTheDocument();
});

test("should error request to api", async () => {
    getUser.mockResolvedValue(dataError)
    const { utils, buttonSearch, inputUser } = renderInit();
    expect(buttonSearch).toBeDisabled();
    user.type(inputUser, "i4334jnrkni43");
    expect(buttonSearch).toBeEnabled();
    user.click(buttonSearch)
    await waitForElementToBeRemoved(()=>utils.getByText(/cargando/i))
    expect(getUser).toHaveBeenCalledWith('i4334jnrkni43')
    expect(getUser).toHaveBeenCalledTimes(1)
});

The problem here is that in the second test the last line expect(getUser).toHaveBeenCalledTimes(1) get error because getUseris calling 2 times, but if I comment the first test, the second pass..

So, how should I do to test this case? Its ok the way that Im doing the tests?

Thanks!

Aucun commentaire:

Enregistrer un commentaire