首页 > 解决方案 > 如何从 react-fetching-library 模拟 useQuery?

问题描述

您好,我如何模拟 useQuery?我有负责调用 api 的容器组件和简单的 ui 组件来为用户显示数据。我收到当前错误

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

容器

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();
  });
});

标签: reactjsjestjsreact-testing-library

解决方案


我认为您可以简单地模拟您的react-fetching-library模块,如下所示:

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

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

// Everything looks the same I guess


推荐阅读