当用户在输入搜索数据中键入一些文本时-testid = 'loading'必须被删除,现在控制台返回Unable to find an element by:[data-testid=“loading”]有人能建议我用SWR写测试或者建议我如何模拟SWR的响应吗
这是我的组件文件
import axios from "axios";
import { useEffect, useState } from "react";
import useSWR from "swr";
import "./styles.css";
const useDebounce = (newValue) => {
const [value, setValue] = useState("");
useEffect(() => {
const timeout = setTimeout(() => {
setValue(newValue);
}, 500);
return () => clearTimeout(timeout);
}, [newValue]);
return value;
};
export const fetcher = async (url) => {
const { data } = await axios.get(url);
return data;
};
export default function App() {
const [query, setQuery] = useState("react");
const searchQuery = useDebounce(query);
const { data: repos } = useSWR(
`https://api.github.com/search/repositories?q=${searchQuery}&per_page=1&page=1`,
fetcher
);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input
testId="search"
data-testid="search"
id="search-input"
placeholder="search"
onChange={(event) => setQuery(event.target.value)}
/>
{!repos ? (
<div data-testid="loader" testId="loader">
<h2 id="loading">loading</h2>
</div>
) : (
repos?.items?.map((user) => {
return (
<div
data-testid="repo-item"
style={{
margin: "1rem",
height: "40px",
background: "lightpink"
}}
>
{user.name}
</div>
);
})
)}
</div>
);
}
这是我的测试文件
import {
render,
screen,
waitForElementToBeRemoved
} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";
import { act } from "react-dom/test-utils";
describe("test", () => {
beforeEach(() => {
jest.resetAllMocks();
jest.useFakeTimers();
});
it("happy render", () => {
expect(() => render(<App />)).not.toThrow();
});
it("renders after search", async () => {
render(<App />);
userEvent.type(screen.getByTestId("search"), "vue");
act(() => {
jest.runAllTimers();
});
await waitForElementToBeRemoved(() => screen.getByTestId("loader"));
});
});
1条答案
按热度按时间h43kikqp1#
您可以模拟
axios.get()
方法及其解析/拒绝的值,而不是模拟useSWR
钩子。然后,测试组件的行为,例如返回数据时呈现的内容,以及没有数据时呈现的内容。例如:
App.tsx
:App.test.tsx
:测试结果: