#javascript #reactjs #axios #react-testing-library #ts-jest
#язык JavaScript #реагирует на #аксиос #реагировать-тестирование-библиотека #тс-шутка
Вопрос:
Я пытаюсь написать модульный тест для своего приложения React и все еще в процессе ознакомления с библиотекой тестирования React.
Я создал пустую страницу, чтобы просто протестировать вызовы api axios, чтобы ознакомиться с ней. У меня есть утилита axios для настройки базовых осей. Когда я следую шагу для тестирования axios, я получил ошибку типа, указанную в названии.
вот мой код утилиты axios:
// axiosUtils.ts import axios from "axios"; import { merge } from "lodash"; import type { AxiosPromise } from "axios"; import { getToken } from "./authUtils"; export const basicAxios = (options: {}): AxiosPromiselt;anygt; =gt; { const token = getToken(); const config = merge({ params: { token } }, options); return axios(config); };
вот тестовый компонент:
// TestPage.tsx const TestPage = () =gt; { const [total, setTotal] = useStatelt;number | nullgt;(null); useEffect(() =gt; { basicAxios({ method: "POST", url: URL, data: payloadBody, }).then(({ data }) =gt; { setTotal(data.total); }); // async function getSummary() { // try { // const { data } = await axios.post(URL, payloadBody); // setTotal(data.total); // } catch (error) { // console.log(error); // } // } // getSummary(); }, []); return ( lt;Containergt; {!total ? ( lt;Loadergt;Loading...lt;/Loadergt; ) : ( lt;divgt; Total amount of return: lt;Label data-testid="label"gt;{total}lt;/Labelgt; lt;/divgt; )} lt;/Containergt; ); }; export default TestPage;
вот моя шутливая установка, чтобы поиздеваться над аксиосом:
//axios.ts export default { __esModule: true, post: jest.fn().mockResolvedValue({ data: {} }), get: jest.fn().mockResolvedValue({ data: {} }), default: jest.fn().mockResolvedValue({ data: {} }), };
Lastly here is my test file:
// TestPage.test.tsx import React from "react"; import { render } from "@testing-library/react"; import axios from "axios"; import "@testing-library/jest-dom/extend-expect"; import TestPage, { URL, payloadBody } from "../TestPage"; const mockedAxios = axios as jest.Mockedlt;typeof axiosgt;; test("show loader when it's fetching data, then render total num", async () =gt; { mockedAxios.post.mockResolvedValueOnce({ data: { aggregations: [], total: 144, }, }); const { findByTestId, getByText } = render(lt;TestPage /gt;); expect(getByText(/loading.../i)).toBeInTheDocument(); const labelValue = await findByTestId("label"); expect(mockedAxios.post).toHaveBeenCalledWith(URL, payloadBody); expect(mockedAxios.post).toHaveBeenCalledTimes(1); });
In my TestPage.tsx, if I use the comment-out code, the test pass without the error. The error occurs when I use basicAxios(used in multiple places in the app). Below is the error log:
TypeError: (0 , _axios.default) is not a function 9 | const token = getToken(); 10 | const config = merge({ params: { token } }, options); gt; 11 | return axios(config); | ^ 12 | }; 13 | at basicAxios (src/lib/axiosUtils.ts:11:10) at src/features/pages/TestPage.tsx:22:5 at invokePassiveEffectCreate (node_modules/react-dom/cjs/react-dom.development.js:23487:20) at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14) at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30) at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25) at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3) at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9) at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17) at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34) at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:3994:16) at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:4056:31) at flushPassiveEffectsImpl (node_modules/react-dom/cjs/react-dom.development.js:23574:9) at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12) at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11276:10) at flushPassiveEffects (node_modules/react-dom/cjs/react-dom.development.js:23447:14) at Object.lt;anonymousgt;.flushWork (node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10) at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1107:9) at render (node_modules/@testing-library/react/dist/pure.js:82:26) at Object.lt;anonymousgt; (src/features/pages/__test__/TestPage.test.tsx:19:39)
У кого — нибудь есть опыт в этом вопросе?