javascript - 使用 Jest 进行测试时 Hook 调用无效 - native react

标签 javascript react-native react-redux jestjs rtk-query

我在测试屏幕时遇到了问题。我正在尝试使用 jest snapshot 进行测试,但首先我不想通过使用 RTK Query request API 的简单测试。在下一个示例中,我尝试得到诸如 Test didn't pass due to not equal results 之类的错误,但我得到了 Invalid hook call 并且更多内容将在示例代码旁边.

ContactScreen-test.js

import 'isomorphic-fetch';
import { useGetUserDataQuery } from '../../services';

describe("testing", () => {
  test("should working properly", () => {
    const result = useGetUserDataQuery();
    console.log(result);
    expect(result).toBe("Idk what");
  });
});

services.ts获取查询/

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { RootState } from '../src/redux/store';

export interface UserResponse {
  data: {
    access_token: string;
    expires_in: number;
    refresh_token: string;
    role: string;
  };
}

export interface LoginRequest {
  email: string;
  password: string;
}

const device_id = '38bda1ce-f795-5cb8-8ae7-4c30b874';

export const callApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: 'api link here',
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).auth.access_token;

      if (device_id) {
        headers.set('Device_Id', device_id);
        headers.set('Authorization', `${token}`);
      }
      return headers;
    }
  }),
  endpoints: builder => ({
    login: builder.mutation<UserResponse, LoginRequest>({
      query: data => ({
        url: '/sessions',
        method: 'POST',
        body: data
      })
    }),
    getUserData: builder.query({
      query: (arg: void) => ({ url: `users/me/`, body: arg })
    }),
    getOfficeData: builder.query({
      query: (office_id: string) => ({ url: `office_contacts/${office_id}` })
    })
  })
});

export const { useLoginMutation, useGetOfficeDataQuery, useGetUserDataQuery } =
  callApi;

我得到的错误是:

 Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

       8 | describe("testing", () => {
       9 |   test("should working properly", () => {
    > 10 |     const result = useGetUserDataQuery();
         |                    ^
      11 |     console.log(result);
      12 |     expect(result).toBe("Idk what");
      13 |   });

最佳答案

您不能像测试普通函数那样测试钩子(Hook)。

为了测试钩子(Hook),你应该使用react-hooks-testing-library .

你可能需要做类似的事情

import { renderHook } from '@testing-library/react-hooks'
import { useGetUserDataQuery } from '../../services';

test('should working properly', () => {
  const { result } = renderHook(() => useGetUserDataQuery())
  expect(result).toBe("Idk what");
})

关于javascript - 使用 Jest 进行测试时 Hook 调用无效 - native react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71558632/

相关文章:

javascript - 如何将两个javascript数组合并为一个并按日期分组

javascript - :inputText does not fire ajax change event when changing its value from javascript

reactjs - react - 偏好 : function component vs class component

javascript - react redux promise middleware 如何将结果 action 发送到 dispatch?

reactjs - RTK查询错误: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

javascript - node.js在函数外获取mysql的结果

javascript - 日期时间选择器在 Bootstrap 中不起作用

react-native - React Native,使用纵向模式检测屏幕旋转变化

javascript - 使用 React Native Webview 添加本地 HTML 和 JS 文件

javascript - react redux 异步 mapStateToProps