Sinon stub - 存根用 swagger 生成的 axios api

问题描述 投票:0回答:0

我有一个由 swagger open api 生成的文件。我正在编写一些测试并第一次使用 sinon 存根。我想知道如何从一个类中存根 api 调用:

export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {

     case = {
        /**
         * @description Create new case
         *
         * @tags case-controller
         * @name CreateCase
         * @request POST:/case
         * @secure
         */
        createCase: (data: CreateCaseRequest, params: RequestParams = {}) =>
            this.request<CreateCaseResponse, any>({
                path: `/case`,
                method: "POST",
                body: data,
                secure: true,
                type: ContentType.Json,
                ...params,
            }),

       findMetadataForCase: (caseNumber: string, params: RequestParams = {}) =>
            this.request<CaseDto, void>({
                path: `/case/${caseNumber}`,
                method: "GET",
                secure: true,
                ...params,
            }),
      }
}

我正在像这样实例化这个 Api:

import { Api as CaseApi } from "../api/CaseApi";
export const CASE_API = useApi(new CaseApi({ baseURL: environment.url.case }), "case", "fss");

我也做了一个处理这个api的文件:

export const useApiData = () => {
    const [networkError, setNetworkError] = useState<string>(null);

    const fetchCase = async (caseNumber: string) => {
        const case = await CASE_API.case.findMetadataForSak(caseNumber);
        return case.data;
    };

    const getCaseAndRoles = (caseNumber: string) => {
        const { data: sak } = useQuery({
            queryKey: `case-${caseNumber}`,
            queryFn: () => fetchCase(caseNumber),
            staleTime: Infinity,
    });

        const { data: roles } = useQuery(
           "roles",
           ({ signal }) => fetchPersons(case, signal).then((persons) => mapPersonsToRoles(case, persons)),
           {
               staleTime: Infinity,
               enabled: !!case
            }
        );

    return { case: case, roles: roles };
};
    const api = {
        getCaseAndRoles,
    };

    return { api, networkError };
};

我想对一个从

getCaseAndRoles
钩子调用
useApiData
的组件进行单元测试。

export const CasePage = () => {
    const { activeStep, setActiveStep, caseNumber } = useCase();
    const { api, networkError } = useApiData();
    const { case, roles } = api.getCaseAndRoles(caseNumber);

    return (...some jsx

我想用假数据测试这个组件:

describe("CasePage", () => {
    it("should render", async () => {
        mockCase();
        render(<CasePage />);
        await waitFor(() => expect(document.querySelector("button")).not.to.be.null);
    });
});

但是,我不确定如何为它创建模拟存根:

export function mockSak(sinonSandbox: SinonSandbox = 
 sinon.createSandbox()) {
    const caseApiMock = sinon.stub(useApiData()).returns({ getCaseAndRoles: () => {} });

    sinonSandbox.stub(caseApiMock, "getCaseAndRoles").callsFake(() => {
            return Promise.resolve(caseTestData);
    });

    return sinonSandbox;
}

但是,那是行不通的,我在运行测试时遇到错误:

    Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我也试过这个:

export function mockCase(sinonSandbox: SinonSandbox = sinon.createSandbox()) {
    sinonSandbox.stub(useApiData).callsFake(() => {
        return { api: { getCaseAndRoles: () => Promise.resolve(caseTestData) } };
    });

    return sinonSandbox;
}

但是,然后我得到以下错误:

TypeError: sinonSandbox.stub(...).callsFake is not a function

我也试过这个:

export function mockSak(sinonSandbox: SinonSandbox = sinon.createSandbox()) {
    sinonSandbox.stub(CaseApi, "case").value({
        findMetadataForCase: () => Promise.resolve(caseTestData),
    });

    return sinonSandbox;
}

但是,然后我得到一个错误:

TypeError: Cannot stub non-existent property case

这很奇怪,因为如果我这样做

CaseApi.property.case
我可以看到它具有该属性。

我怎样才能存根这个 api 调用?

reactjs typescript react-hooks sinon stub
© www.soinside.com 2019 - 2024. All rights reserved.