-1

如何测试调用 get API 并输出响应的函数。我试过了,但我能够测试处于状态的初始数据,但我想知道如何测试调用 API 时更新初始状态的函数。

代码示例我尝试过的内容。CodeSandboxLink : [测试代码] 1

上下文 API

在这里,我调用了上下文中的函数userDataFunc ,初始数据存储在状态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>
    );
  }
}

上下文测试文件

在这里,我执行了一些测试,例如通过测试用例的初始状态值,但我无法测试该功能,任何人都可以帮助我。

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 () => {});
});

4

1 回答 1

0

我认为您应该通过使用它的组件上显示的内容来测试 API 调用。例如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,并通过稍微修改你的GprovDashboard组件,这里是代码:

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>
  );
}
于 2021-03-03T14:42:09.583 回答