【问题标题】:How testing my API calls in differents groups of test?如何在不同的测试组中测试我的 API 调用?
【发布时间】:2020-11-28 02:05:18
【问题描述】:

我从 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 次,但是如果我评论第一个测试,第二个通过..

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

谢谢!

【问题讨论】:

    标签: javascript reactjs api testing integration-testing


    【解决方案1】:

    您可以将jest.mockClear()beforeEach()afterEach() 一起使用

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

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

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

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

    【讨论】:

    • 谢谢,它使用clearAllMocks .. 也感谢其他项目!
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2018-02-16
    • 2013-09-08
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多