我先从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()
})
此外,使用screen
@ testing-library / react而不是render
使用查询时的返回值。同样,mockResolvedValueOnce
在这种情况下会更好。
谢谢,它可以使用
clearAllMocks
..并也感谢其他物品!