使用 jest 测试时无效的钩子调用 - React Native

Mik*_*odt 7 javascript jestjs react-native react-redux 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");
  });
});
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

 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 |   });
Run Code Online (Sandbox Code Playgroud)

Ven*_*sky 12

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

对于测试钩子,您应该使用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");
})
Run Code Online (Sandbox Code Playgroud)

  • 好的,明白了,但我的目标不是测试钩子,而是测试整个屏幕/组件。如果我不能像这样放置挂钩,那我该怎么办?就像这些文档写下的那样:“什么时候不使用这个库 1. 你的钩子是与组件一起定义的,并且只在那里使用 2. 你的钩子很容易通过使用它测试组件来测试” 所有要点都是正确的 (2认同)