• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ericgui
V2EX  ›  程序员

[前端] 最近在写 axios 的 unit test,太痛苦了

  •  
  •   ericgui · Oct 29, 2022 · 3606 views
  •   You need to sign in to view this topic
    This topic created in 1430 days ago, the information mentioned may be changed or developed.

    有人玩过的吗?

    尤其是 interceptor ,这个玩意儿的测试怎么写

    我发现这个库,但似乎也没写怎么用 interceptor 的例子

    https://github.com/knee-cola/jest-mock-axios

    7 replies  •  2022-11-01 01:35:43 +08:00
    zhyd1997
        1
    zhyd1997  
       Oct 29, 2022   ❤️ 3
    johnkiller
        2
    johnkiller  
       Oct 29, 2022
    一楼正解
    jones2000
        3
    jones2000  
       Oct 29, 2022
    mock 以后很多网络错误就不能测试出来了。超时,丢包,代理修改数据包, 浏览器请求队列满了, 等等。
    hamsterbase
        4
    hamsterbase  
       Oct 29, 2022
    1. 页面不要直接依赖 axios ,抽象一个 requestService 出来

    interface RequestService {
    get<T>(url: string): Promise<T>;
    }

    class UserService {
    constructor(private request: RequestService) {}

    getUser(id: string) {
    return this.request.get<{ name: string }>(`user/${id}`);
    }
    }

    function useService() {
    return new UserService({} as any);
    }

    const Page: React.FC<{ id: string }> = (props) => {
    const service = useService();
    const [name, setName] = useState();
    useEffect(() => {
    service.getUser(props.id).then((response) => {
    setName(name);
    });
    }, [props.id]);

    return <div>{name}</div>;
    };



    2. 可以直接对 axios 进行集成测试。 本地起一个 node 服务,拿 AxiosRequestService 去请求这个服务。
    或者是利用 httpbin 等在线服务

    interface RequestService {
    get<T>(url: string): Promise<T>;
    }

    class AxiosRequestService implements RequestService {
    get() {
    axios.get('......');
    }
    }
    hamsterbase
        5
    hamsterbase  
       Oct 29, 2022
    1. 测业务逻辑的时候,拿 mock 的 RequestService 测试业务逻辑。

    2. 测 axios 中间件的时候, 拿真实的 http 请求去测 axios 。
    ericgui
        6
    ericgui  
    OP
       Oct 30, 2022
    @hamsterbase 第二条,确定吗?单元测试用真实的 http ?
    MrHyde
        7
    MrHyde  
       Nov 1, 2022
    @jones2000 我司现在的垃圾代码,连普通的 http request error 都测不出来呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5424 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 75ms · UTC 02:35 · PVG 10:35 · LAX 19:35 · JFK 22:35
    ♥ Do have faith in what you're doing.