【问题标题】:Getting undefined from useQuery hook in Jest test从 Jest 测试中的 useQuery 挂钩中获取未定义
【发布时间】:2023-01-26 04:20:19
【问题描述】:

我有以下 useQuery 钩子用法:

const { data: user, refetch } = useQuery({
    queryKey: ['user', userId],
    queryFn: () =>
      UserApi.getUserById(userId)
        .then(({ data }) => data)
        .catch(() => {
          NotificationManager.error('Error with getting user with id: ' + userId, { icon: true });
        })
  });

这在我的组件中工作正常,但我在测试时遇到问题:

import React from 'react';
import { screen } from '@testing-library/react';

import '@testing-library/jest-dom';

import { UserApi } from '../../api';
import { render } from '../../config/test/root-render';
import useCurrentUserInfo from '../../hooks/useCurrentUserInfo';

import UserDetails from './UserDetails';

jest.mock('../../api/UserApi');
jest.mock('../../hooks/useCurrentUserInfo');
jest.mock('../../root/router', () => {
  return {
    useCurrentRoute: () => ({ params: { userId: 'userId' }, parent: { key: '' } }),
    generateUrlByKey: () => '1'
  };
});

function mockApi(userFiles, userStatus, userSecondaryStatus) {
  UserApi.getUserById = jest.fn().mockReturnValue(
    new Promise((resolve) =>
      resolve({
        data: { userFiles: userFiles, general: { status: userSecondaryStatus}, userStatus: userStatus}
      })
    )
  );
}

function mockAndRender(userFiles, userStatus, userSecondaryStatus) {
  useCurrentUserInfo.mockReturnValue([{}]);
  mockApi(userFiles, userStatus, userSecondaryStatus);
  render(<UserDetails />);
}

describe('<UserDetails />', () => {
  it('test', () => {
    mockAndRender([1], 'Awarded', null)
  })
})

如您所见,我没有模拟 useQuery 挂钩,因为我不需要它。我必须模拟 api 调用而不是挂钩。此外,模拟我的 api 调用按预期工作(我已经用调试器检查并验证了它),但 useQuery 返回未定义。有没有人知道如何解决它?

【问题讨论】:

  • 你是说userQuery返回的dataundefined
  • 部分你是对的,const { data: user, refetch } = useQuery(...)中的dataundefined,但.then(({ data }) =&gt; data)中的data具有我在测试中的模拟API函数中提供的正确值。

标签: reactjs unit-testing react-testing-library react-query


【解决方案1】:

所以,经过深入研究,我找到了问题的根源。上面描述的代码是正确的。但是问题出在我没有在问题中提供的行中。

expect(screen.getByTestId('username')).toBeInTheDocument();

方法 getByTestId 获取数据的速度比定义数据的速度快。将代码更改为此后,它按预期工作:

expect(await screen.findByTestId('username')).toBeInTheDocument();

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2023-01-24
    • 2022-01-13
    • 2022-06-30
    相关资源
    最近更新 更多