0

Hello how can I mock useQuery? I have container component which is responsible for calling an api, and simple ui component to display data for the user. I'm receiving current error

console.error node_modules/@testing-library/react/dist/act-compat.js:52
Error: Error: connect ECONNREFUSED 127.0.0.1:80

Container

import React from 'react';
import { screen, waitForElement, getByText } from '@testing-library/react';
import { useQuery } from 'react-fetching-library';

import { render } from 'tests';
import tags from 'api/mocks/tags-response.json';

import { TrendingTagsContainer } from './TrendingTagsContainer';
jest.mock('react-fetching-library');

describe('TrendingTagsContainer component', () => {
  test('should render component with correct title and description', async () => {
    const action = jest.fn();
    const useQuery = jest.fn(action());
    useQuery.mockReturnValue({ loading: false, error: false, query: () => true, payload: { tags } });
    console.log(useQuery());
    const { getByText } = render(<TrendingTagsContainer />);
    await waitForElement(() => screen.getByText('#Testing react'));
    expect(screen.getByText('#Testing react')).toBeInTheDocument();
  });
});

1 Answer 1

1

I think you can simply you mock your react-fetching-library module as following:

import { useQuery } from 'react-fetching-library';

jest.mock('react-fetching-library');

// Everything looks the same I guess

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks, however this solution still try to fetch external api
Error: Error: connect ECONNREFUSED 127.0.0.1:80 at Object.dispatchError
I’m not sure if useQuery will be called multiple times so try to mock all the time instead of just once by using mockImplentation
It is in the top of the file, it helped with resolving the error with calling api. Thanks!
Yes I don't have error with refused conection, now it's only about some test wrapper issue, Thank you very much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.