最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Invalid hook call while testing with jest - react native - Stack Overflow

programmeradmin0浏览0评论

I've got problem with testing screen. I'm trying to test with jest snapshot but first of all I wan't to pass simple test with RTK Query request API. In next example I try to get error something like Test didn't pass due to not equal results but I'm getting Invalid hook call and more will be next to example code.

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

Which getting query from 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;

and error which I'm getting is:

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

I've got problem with testing screen. I'm trying to test with jest snapshot but first of all I wan't to pass simple test with RTK Query request API. In next example I try to get error something like Test didn't pass due to not equal results but I'm getting Invalid hook call and more will be next to example code.

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

Which getting query from 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;

and error which I'm getting is:

 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 |   });
Share Improve this question asked Mar 21, 2022 at 13:43 Mikołaj WittbrodtMikołaj Wittbrodt 4651 gold badge6 silver badges23 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 15

You can't test hooks as you would test a normal function.

For testing hooks, you should use react-hooks-testing-library.

You would probably need to do something like

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

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

评论列表(0)

  1. 暂无评论