”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 反应基础〜单位测试/异步测试

反应基础〜单位测试/异步测试

发布于2025-03-12
浏览:754
  • 当我测试ASYNC操作时,我在测试代码中使用异步/等待。

    我需要为测试数据做准备。在这种情况下,我使用JSON服务器。

  • ・模拟/db.json

{ “用户”:[ { “ id”:1, “名称”:“ foo” } 这是给出的 }

[2

“脚本”:{ “ dev”:“ vite”, “开始”:“ Vite”, “构建”:“ Vite Build”, “测试”:“ vitest”, “预览”:“ Vite Preview”, //↓设置JSON服务器的脚本 “ JSON -SERVER”:“ NPX JSON -SERVER -W ./mock/db.json -p 4030” },,
{
  "users": [
    {
      "id": 1,
      "name": "Foo"
    }
  ]
}

,然后我必须运行一个命令。


NPM运行json-server
{
  "users": [
    {
      "id": 1,
      "name": "Foo"
    }
  ]
}

・ src/example.js


从“ ./components/getuserdata”; //测试数据的路径 导出const endpoint_url ='http:// localhost:4030/users/1'; const example =()=> { 返回 ( > ); }; 导出默认示例;
{
  "users": [
    {
      "id": 1,
      "name": "Foo"
    }
  ]
}


= usestate(null); useeffect(()=> { axios.get(url)。 // eslint-disable-next-line反应钩/详尽的deps },[]); 返回 (

{userdata? ((

配置文件

  • id:{userdata.id}
  • 名称:{userdata.name}
> ):((

...加载

); }; 导出默认getUserData;
import GetUserData from "./components/GetUserData";

//The path of test data
export const ENDPOINT_URL = 'http://localhost:4030/users/1';

const Example = () => {
  return (
    
      
    >
  );
};

export default Example;

.TextContent).tobe(“ ID:1”); 期望(itemels [1] .textContent).tobe(“名称:foo”); }); });

import { useEffect, useState } from "react";
import axios from "axios";

const GetUserData = ({ url }) => {
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    axios.get(url).then((response) => setUserData(response.data));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    
{userData ? (

Profile

  • ID: {userData.id}
  • Name: {userData.name}
> ) : (

...loading

)}
); }; export default GetUserData;
[2

因为测试在没有用户数据的情况下继续。

import { render, screen } from "@testing-library/react";
import GetUserData from "./GetUserData";
import { ENDPOINT_URL } from "../Example";

describe("Check an action of The GetUserData component", () => {

  test("External data fetching in progress", () => {
    render();
    const h1El = screen.getByRole("heading", { name: "...loading" });
    expect(h1El).toBeInTheDocument();
  });

  ★ Not using  async/await
  test("After external data fetching",  () => {
    render();
    const h2El =  screen.findByRole("heading", { name: "Profile" });
    expect(h2El).toBeInTheDocument();

    const itemEls =  screen.findAllByRole("listitem");

    expect(itemEls[0].textContent).toBe("ID: 1");
    expect(itemEls[1].textContent).toBe("Name: Foo");
  });
});

.TextContent).tobe(“ ID:1”); 期望(itemels [1] .textContent).tobe(“名称:foo”); }); });
  • 如果我使用async/等待,则测试成功。

[2 React Basics~unit test/async test

展示

[2


版本声明 本文转载于:https://dev.to/kkr0423/react-basicsunit-testasync-test-28g?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3