如何在不同的测试组中测试我的 API 调用?

How testing my API calls in differents groups of test?

我从 react-testing-library 开始,我正在尝试测试 API 调用。我有两套,一套用于成功请求,另一套用于错误请求。

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)
});

这里的问题是,在第二次测试中,最后一行 expect(getUser).toHaveBeenCalledTimes(1) 出错,因为 getUser 调用了 2 次,但是如果我评论第一次测试,第二次通过..

那么,我应该怎么做才能测试这个案例呢?我做测试的方式可以吗?

谢谢!

您可以将 jest.mockClear()beforeEach()afterEach()

一起使用

出于清理目的,afterEach() 更合适。

mockClear 重置存储在 mockFn.mock.calls 中的所有信息,这意味着对于每个测试,您可以期望 getUser 被调用,从零开始。

afterEach(() => {
  jest.clearAllMocks()
})

此外,在使用查询时,使用来自@testing-library/react 的screen 而不是render 的返回值。另外,在这种情况下,mockResolvedValueOnce 会更好。