如何使用useEffect钩子和异步调用编写React Component单元测试?

时间:2020-04-08 19:59:00

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

我从一个基本的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);
    });
});

1 个答案:

答案 0 :(得分:0)

谢谢@diedu的评论。那为我指明了正确的方向。这是最终的工作测试:

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);
});