【问题标题】:How to write a React Component unit test with useEffect hook and async call?如何使用 useEffect 钩子和异步调用编写 React 组件单元测试?
【发布时间】:2020-04-08 19:59:00
【问题描述】:

我从一个基本的 create-react-app 应用程序开始,并尝试学习正确的单元测试技术。我更新了初始 App 组件以调用本地节点 API 以获取基本字符串响应。我似乎无法在文档中找到有关如何测试段落标记是否是我的测试中的模拟响应的文档。

发生的事情是组件只是停留在初始的“Hello World!”上来自状态消息的文本,而不是使用模拟的响应消息进行更新。我确定我必须触发更新或完成各种摘要循环,但我还不确定如何做到这一点。

App.js

import React from "react";
import axios from "axios";
import "./App.css";

const App = () => {
  const [message, setMessage] = React.useState("Hello World!");

  React.useEffect(() => {
    const getGreetingFromApi = async () => {
      const apiResponseGreeting = await axios.get("api/hello");
      setMessage(apiResponseGreeting.data);
    };
    getGreetingFromApi();
  });

  return (
    <div className="App">
      <header className="App-header">
        <p>{message}</p>
      </header>
    </div>
  );
};

export default App;

App.test.js

import React from "react";
import ReactDOM from "react-dom";
import { act } from "react-dom/test-utils";

import axios from "axios";
import App from "./App";

jest.mock("axios");

describe("App Component Tests", () => {

    let container;

    beforeEach(() => {
        container = document.createElement("div");
        document.body.appendChild(container);
    });

    afterEach(() => {
        document.body.removeChild(container);
        container = null;
    });

    it("App replaces initial value with greeting response", async () => {
        const mockResponse = { data: "Label Test Text" };
        axios.get.mockResolvedValue(mockResponse);

        let paragraph;

        act(() => {
            ReactDOM.render(<App />, container);
            paragraph = container.querySelector("p");
        });

        expect(paragraph.textContent).toEqual(mockResponse.data);
    });
});

【问题讨论】:

标签: javascript reactjs unit-testing testing react-hooks


【解决方案1】:

感谢@diedu 的cmets。这为我指明了正确的方向。这是最后的工作测试:

it("App replaces initial value with greeting response", async () => {
    const mockResponse = { data: "Label Test Text" };
    axios.get.mockResolvedValue(mockResponse);

    let paragraph;

    await act(async () => {
      await ReactDOM.render(<App />, container);
      paragraph = container.querySelector("p");
    });

    expect(paragraph.textContent).toEqual(mockResponse.data);
});

【讨论】:

  • 学习新技能总是很有趣! react testing library 让我很幸运。它会为您处理一些act 包装位。
猜你喜欢
  • 2021-11-07
  • 2021-10-22
  • 2021-10-30
  • 2020-12-16
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多