Насмешливые запросы на получение axios и API

#typescript #jestjs #react-hooks #react-testing-library

Вопрос:

Я пишу интеграционный тест для формы, которая получает множество значений, одно из которых получает свои данные из другой конечной точки, которая не является ее собственной.

 /* eslint-disable camelcase */
import React from 'react';
import userEvent from '@testing-library/user-event';
import {
  cleanup, screen, act, waitFor, fireEvent, renderWithRecoilSnapshot,
} from 'testWrapper';
import * as institution from 'services/adminModules/institution';
import {
  generateMockInstitution, mockAxiosResponse,
} from 'helpers/testMocks';
import selectEvent from 'react-select-event';
import { institutionTypeAtom } from 'recoil/institution/institutionType';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import InstitutionForm from '../../views/app/admin/InstitutionsPage/InstitutionForm';

let createInstitution: jest.SpyInstance;

const file = new File(['file contents'], 'teste.png', { type: 'image/png' });

const mockInstitution = generateMockInstitution(file);

const mockData: any = [
  { institution_type: 'Pública', institution_type_id: mockInstitution.institution_type_id },
];

const mockSubmit = jest.fn().mockReturnValue(mockInstitution);
const mockClose = jest.fn();
const mock = new MockAdapter(axios);

const renderComponent = () => renderWithRecoilSnapshot(
  <InstitutionForm
    handleClose={mockClose}
    handleSubmit={mockSubmit}
  />,
  ({ set }) => {
    set(institutionTypeAtom, mockData);
  },
);

describe('InstitutionFormPage', () => {
  afterEach(() => {
    cleanup();
  });
  beforeEach(() => {
    createInstitution = jest.spyOn(institution, 'createInstitution').mockImplementation(async () => mockAxiosResponse());
    jest.spyOn(institution, 'getInstitution').mockImplementation(async () => mockAxiosResponse());
  });

  it('Should submit Institution Form', async () => {
    const { container } = renderComponent();
    const data = mock.onGet('/institution-types').reply(200, mockData);

    await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());


    const institution_type_id = screen.getByLabelText('institution_type_id');

    
    expect(institution_type_id).toBeInTheDocument();

    await act(async () => {
      await selectEvent.select(institution_type_id, mockData.map((d: any) => d.institution_type));
    });

    const institution_logo = screen.getByLabelText('institution_logo_file');

    const button = screen.getByRole('button', { name: /SALVAR/i });
    expect(button).toBeInTheDocument();

    await act(async () => {
      await userEvent.click(button);
    });

    await waitFor(() => expect(
      mockSubmit,
    ).toHaveBeenCalledWith(mockInstitution, expect.anything()));
  });
});
 

И я получаю свои высмеянные значения из другого файла:

 export const generateMockInstitution = (file: File): InstitutionFormType => ({
  institution_type_id: faker.datatype.uuid(),
  deleted: false,
});
 

Тест, как он есть, работает и проходит, как и ожидалось, без необходимости использования API, как и должно быть. Но по какой-то причине он все еще говорит мне, что пытается извлечь данные из API сервера, и регистрирует ошибки как таковые:

 console.error src/services/adminModules/institution.ts:22
      Error on institution get: TypeError: Cannot read property 'data' of undefined
    console.error node_modules/filter-console/index.js:46
      Error: Error: connect ECONNREFUSED 
 

Я попытался высмеять ответ axios с помощью адаптера axios-mock, но безрезультатно, так как ошибка не исчезнет. Код, который я пробовал, остался в тесте, и я также пытался издеваться над axios с помощью шутки, но получаю ошибки, когда заголовки и перехватчики не определены или недоступны.

Как бы я правильно издевался над запросом API для этого теста? Или, по крайней мере, сделать так, чтобы предупреждение исчезло?

Комментарии:

1. Возможно, вам захочется поиздеваться над запросом перед визуализацией вашего компонента.

2. Понял! Спасибо!