如何测试调用api的函数? [英] How to test function which call api?
问题描述
如何测试调用get API并输出响应的函数.我尝试过,但是我可以测试处于状态的初始数据,但是我想知道如何测试调用API时更新初始状态的函数.
How to test a function which call get API and output a response. I tried but I am able to test initial data which is in state , but I want to know how to test the function which updates the initial state when the API is called .
代码示例我尝试过的.CodeSandboxLink:[测试代码] 1
code Example what I have Tried. CodeSandboxLink : [testing code]1
上下文API
这里我调用了函数 userDataFunc ,该函数位于上下文中,初始数据存储在状态 userData
Here I have called the function userDataFunc which is in context and initial data is stored in state userData
import React, { Component, createContext } from "react";
import axios from "axios";
export const globalC = createContext();
export class Gprov extends Component {
state = {
userData: []
};
componentDidMount() {}
userDataFunc = async () => {
await axios(`https://jsonplaceholder.typicode.com/users`)
.then((res) => {
if (res.status === 200) {
this.setState({
userData: res.data
});
}
})
.catch((err) =>
this.setState({
userDataerror: err
})
);
};
render() {
return (
<globalC.Provider
value={{
...this.state,
userDataFunc: this.userDataFunc
}}
>
{this.props.children}
</globalC.Provider>
);
}
}
上下文测试文件
在这里,我已经执行了一些测试,例如通过测试用例的初始状态值,但是我无法测试该功能,谁能帮助我.
Here I have performed some test such as initial state value which passes the test cases but i not able to test the function can anyone help me out .
import React from "react";
import { Gprov } from "./context";
import { create } from "react-test-renderer";
import { waitForElement, cleanup } from "@testing-library/react";
import axiosMock from "axios";
afterEach(cleanup)
describe("Context Page", async () => {
const component = create(<Gprov />);
const instance = component.getInstance();
it("it updates dose correctly", () => {
console.log("instance", instance);
expect(instance.state.userData).toStrictEqual([]);
});
it("fetches data and display", async () => {});
});
推荐答案
我认为您应该通过使用它的组件上显示的内容来测试API调用.例如 Dashboard
.
I think you should test the API call through what is displayed on the components that use it. For example Dashboard
.
这是我为 Dashboard
编写的测试:
import React from "react";
import Dashboard from "./Dashboard";
import { Gprov } from "./context";
import { render, waitFor } from "@testing-library/react";
import axios from "axios";
import "@testing-library/jest-dom/extend-expect";
jest.mock("axios");
afterEach(() => {
jest.clearAllMocks();
});
it("displays user name in dashboard", async () => {
axios.mockResolvedValue({ data: { id: 1, name: "John" }, status: 200 });
const { getByText } = render(
<Gprov>
<Dashboard />
</Gprov>
);
await waitFor(() => expect(getByText("John")).toBeInTheDocument());
});
我通过使用 create-react-app
创建的新项目并通过稍微修改您的 Gprov
和 Dashboard
组件来使它通过,这是代码:
I made it pass in a new project I created with create-react-app
, and by slightly modifying your Gprov
and Dashboard
components, here is the code:
export class Gprov extends Component {
state = {
userData: [],
};
componentDidMount() {}
userDataFunc = async () => {
await axios(`https://jsonplaceholder.typicode.com/users`)
.then((res) => {
if (res.status === 200) {
this.setState({
userData: [...this.state.userData, res.data],
});
}
})
.catch((err) => {
this.setState({
userDataerror: err,
});
});
};
render() {
return (
<globalC.Provider
value={{
...this.state,
userDataFunc: this.userDataFunc,
}}
>
{this.props.children}
</globalC.Provider>
);
}
}
export default function Dashboard() {
const { userDataFunc, userData } = useContext(globalC);
useEffect(() => {
userDataFunc();
}, []);
return (
<div
style={{ height: "100vh", backgroundColor: "#ea2345" }}
className="d-flex justify-content-center align-items-center"
>
<div
style={{
overflowY: "auto",
margin: "4px",
border: "2px solid",
padding: "12px",
height: "80vh",
}}
>
{userData &&
userData.map((i) => {
return (
<h5 key={i.id} style={{ color: "#fff" }}>
{i.name}
</h5>
);
})}
</div>
</div>
);
}
这篇关于如何测试调用api的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!