2

I'm writing a test in React for a component that will display a destination together with an IATA code (airport code). So far I have followed multiple tutorials but currently the test will only detect the loading state. As you can see the mocked API response is empty. What am I missing?

Empty response from mocked API

Destination.js:

import React from 'react';
import axios from 'axios';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { useQuery } from 'react-query';

const query = async (key) => {
  const { data } = await axios.get(
    `${process.env.REACT_APP_API_BASE_URL}${key}`
  );
  return data;
};

const Destination = ({ route, className }) => {
  const { status, data: result, error, isFetching } = useQuery(
    `/destinations/${route.destinations[0]}`,
    query,
    {
      staleTime: Infinity,
      cacheTime: Infinity,
    }
  );

  return (
    <>
      {isFetching ? (
        <span data-testid="loading" className={className}>
          Loading...
        </span>
      ) : error ? (
        <span className={className}>Error</span>
      ) : result ? (
        <span data-testid="resolved" className={className}>
          {result.city} ({result.iata})
        </span>
      ) : (
        <span data-testid="nodata" className={className}>
          No data
        </span>
      )}
    </>
  );
};

Destination.test.js:

import React from 'react';
import {
  render,
  cleanup,
  screen,
  waitForElement,
} from '@testing-library/react';
import { Destination } from './Destination';
import axiosMock from 'axios';

afterEach(cleanup);

describe('Destination', () => {
  it('Renders <Destination /> component', async () => {
    const route = { destinations: ['GVA'] };
    const url = `${process.env.REACT_APP_API_BASE_URL}/destinations/GVA`;

    axiosMock.get.mockResolvedValueOnce({
      result: { city: 'Geneva', iata: 'GVA' },
    });

    render(<Destination route={route} />);

    expect(screen.getByTestId('loading')).toHaveTextContent('Loading...');
    const spanResolved = await waitForElement(() =>
      screen.getByTestId('resolved')
    );
    expect(spanResolved).toHaveTextContent('Geneva (GVA)');

    expect(axiosMock.get).toHaveBeenCalledTimes(1);
    expect(axiosMock.get).toHaveBeenCalledWith(url);
  });
});

axios.js mock file in mocks:

export default {
  get: jest.fn().mockResolvedValue({ result: {} }),
};

  • Please flow this link I guess there is a solution for your case [How do I test axios in jest](https://stackoverflow.com/questions/45016033/how-do-i-test-axios-in-jest) – Bablu Ahmed Nov 17 '20 at 18:51

0 Answers0