Skip to content

Commit

Permalink
remove outstanding testing-library/react-hooks usages (elastic#205307)
Browse files Browse the repository at this point in the history
## Summary

This PR removes usages of `@testing-library/react-hooks` from the
codebase, as we've transitioned to using `@testing-library/react`
especially that it provides the same utils we need and the later package
is not supported for react 18. alongside this ~other instance of the
usages for `@testing-library/react-hooks` have been removed~ an eslint
rule has been enabled to prevent further usages of the mentioned
package.

<!--
### Checklist

Check the PR satisfies following conditions. 

Reviewers should verify this PR satisfies this list as well.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

Does this PR introduce any risks? For example, consider risks like hard
to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified
risk. Invite stakeholders and evaluate how to proceed before merging.

- [ ] [See some risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
- [ ] ...


-->

---------

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
eokoneyo and elasticmachine authored Jan 7, 2025
1 parent d0166b6 commit 1c3f7a6
Show file tree
Hide file tree
Showing 24 changed files with 73 additions and 80 deletions.
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,10 @@ const RESTRICTED_IMPORTS = [
message:
'Please, use rxjs instead: rxjs/operators is just a subset, unnecessarily duplicating the package import.',
},
{
name: '@testing-library/react-hooks',
message: 'Please use @testing-library/react instead',
},
];

module.exports = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
Expand All @@ -32,7 +32,7 @@ describe('useFindAlertsQuery', () => {
});

it('calls the api correctly', async () => {
const { result, waitForValueToChange } = renderHook(
const { result } = renderHook(
() =>
useFindAlertsQuery({
...mockServices,
Expand All @@ -43,7 +43,7 @@ describe('useFindAlertsQuery', () => {
}
);

await waitForValueToChange(() => result.current.isLoading, { timeout: 5000 });
await waitFor(() => expect(result.current.isLoading).toBe(true), { timeout: 5000 });

expect(mockServices.http.post).toHaveBeenCalledTimes(1);
expect(mockServices.http.post).toBeCalledWith('/internal/rac/alerts/find', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/

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

describe('share menu context', () => {
describe('useShareTabsContext', () => {
it('throws an error if used outside of ShareMenuProvider tree', () => {
const { result } = renderHook(() => useShareTabsContext());

expect(result.error?.message).toEqual(
expect.stringContaining(
'Failed to call `useShareTabsContext` because the context from ShareMenuProvider is missing.'
)
expect(() => renderHook(() => useShareTabsContext())).toThrow(
/^Failed to call `useShareTabsContext` because the context from ShareMenuProvider is missing./
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import {
useCreateKnowledgeBaseEntry,
UseCreateKnowledgeBaseEntryParams,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import {
useDeleteKnowledgeBaseEntries,
UseDeleteKnowledgeEntriesParams,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { useKnowledgeBaseEntries } from './use_knowledge_base_entries';
import { HttpSetup } from '@kbn/core/public';
import { IToasts } from '@kbn/core-notifications-browser';
Expand All @@ -27,40 +27,40 @@ describe('useKnowledgeBaseEntries', () => {
data: [{ id: '1', title: 'Entry 1' }],
});

const { result, waitForNextUpdate } = renderHook(
const { result } = renderHook(
() => useKnowledgeBaseEntries({ http: httpMock, enabled: true }),
{
wrapper: TestProviders,
}
);
expect(result.current.fetchStatus).toEqual('fetching');

await waitForNextUpdate();

expect(result.current.data).toEqual({
page: 1,
perPage: 100,
total: 1,
data: [{ id: '1', title: 'Entry 1' }],
});
await waitFor(() =>
expect(result.current.data).toEqual({
page: 1,
perPage: 100,
total: 1,
data: [{ id: '1', title: 'Entry 1' }],
})
);
});

it('handles fetch error', async () => {
const error = new Error('Fetch error');
(httpMock.fetch as jest.Mock).mockRejectedValue(error);

const { waitForNextUpdate } = renderHook(
renderHook(
() => useKnowledgeBaseEntries({ http: httpMock, toasts: toastsMock, enabled: true }),
{
wrapper: TestProviders,
}
);

await waitForNextUpdate();

expect(toastsMock.addError).toHaveBeenCalledWith(error, {
title: 'Error fetching Knowledge Base entries',
});
await waitFor(() =>
expect(toastsMock.addError).toHaveBeenCalledWith(error, {
title: 'Error fetching Knowledge Base entries',
})
);
});

it('does not fetch when disabled', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import {
useUpdateKnowledgeBaseEntries,
UseUpdateKnowledgeBaseEntriesParams,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { CaseStatuses } from '../../../../common/types/domain';
import { useUserPermissions } from '../../user_actions/use_user_permissions';
import { useShouldDisableStatus } from './use_should_disable_status';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useCaseObservables } from './use_case_observables';
import { useGetCaseConfiguration } from '../../containers/configure/use_get_case_configuration';
import { OBSERVABLE_TYPES_BUILTIN_KEYS } from '../../../common/constants';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useCasesContext } from '../cases_context/use_cases_context';
import { useUserPermissions } from './use_user_permissions';
import type { UserActivityParams } from '../user_actions_activity_bar/types';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act, waitFor } from '@testing-library/react';
import { useDeleteObservable } from './use_delete_observables';
import { deleteObservable } from './api';
import { useCasesToast } from '../common/use_cases_toast';
Expand Down Expand Up @@ -35,7 +35,7 @@ describe('useDeleteObservable', () => {
it('should call deleteObservable and show success toast on success', async () => {
(deleteObservable as jest.Mock).mockResolvedValue({});

const { result, waitFor } = renderHook(() => useDeleteObservable(caseId, observableId), {
const { result } = renderHook(() => useDeleteObservable(caseId, observableId), {
wrapper: appMockRender.AppWrapper,
});

Expand All @@ -52,7 +52,7 @@ describe('useDeleteObservable', () => {
const error = new Error('Failed to delete observable');
(deleteObservable as jest.Mock).mockRejectedValue(error);

const { result, waitFor } = renderHook(() => useDeleteObservable(caseId, observableId), {
const { result } = renderHook(() => useDeleteObservable(caseId, observableId), {
wrapper: appMockRender.AppWrapper,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import * as api from './api';
import type { AppMockRenderer } from '../common/mock';
import { createAppMockRenderer } from '../common/mock';
Expand All @@ -30,12 +30,9 @@ describe('useGetSimilarCases', () => {

it('calls getSimilarCases with correct arguments', async () => {
const spyOnGetCases = jest.spyOn(api, 'getSimilarCases');
const { waitFor } = renderHook(
() => useGetSimilarCases({ caseId: mockCase.id, perPage: 10, page: 0 }),
{
wrapper: appMockRender.AppWrapper,
}
);
renderHook(() => useGetSimilarCases({ caseId: mockCase.id, perPage: 10, page: 0 }), {
wrapper: appMockRender.AppWrapper,
});

await waitFor(() => {
expect(spyOnGetCases).toBeCalled();
Expand All @@ -58,12 +55,9 @@ describe('useGetSimilarCases', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess, addError });

const { waitFor } = renderHook(
() => useGetSimilarCases({ caseId: mockCase.id, perPage: 10, page: 0 }),
{
wrapper: appMockRender.AppWrapper,
}
);
renderHook(() => useGetSimilarCases({ caseId: mockCase.id, perPage: 10, page: 0 }), {
wrapper: appMockRender.AppWrapper,
});

await waitFor(() => {
expect(addError).toHaveBeenCalled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act, waitFor } from '@testing-library/react';
import { usePatchObservable } from './use_patch_observables';
import { patchObservable } from './api';
import { useCasesToast } from '../common/use_cases_toast';
Expand Down Expand Up @@ -41,7 +41,7 @@ describe('usePatchObservable', () => {
it('should call patchObservable and show success toast on success', async () => {
(patchObservable as jest.Mock).mockResolvedValue({});

const { result, waitFor } = renderHook(() => usePatchObservable(caseId, observableId), {
const { result } = renderHook(() => usePatchObservable(caseId, observableId), {
wrapper: appMockRender.AppWrapper,
});

Expand All @@ -60,7 +60,7 @@ describe('usePatchObservable', () => {
const error = new Error('Failed to patch observable');
(patchObservable as jest.Mock).mockRejectedValue(error);

const { result, waitFor } = renderHook(() => usePatchObservable(caseId, observableId), {
const { result } = renderHook(() => usePatchObservable(caseId, observableId), {
wrapper: appMockRender.AppWrapper,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act, waitFor } from '@testing-library/react';
import * as api from './api';
import { useToasts } from '../common/lib/kibana';
import type { AppMockRenderer } from '../common/mock';
Expand Down Expand Up @@ -41,63 +41,57 @@ describe('usePostObservables', () => {

it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'postObservable');
const { waitForNextUpdate, result } = renderHook(() => usePostObservable(mockCase.id), {
const { result } = renderHook(() => usePostObservable(mockCase.id), {
wrapper: appMockRender.AppWrapper,
});

act(() => {
result.current.mutate(observableMock);
});

await waitForNextUpdate();

expect(spy).toHaveBeenCalledWith({ observable: observableMock.observable }, mockCase.id);
await waitFor(() =>
expect(spy).toHaveBeenCalledWith({ observable: observableMock.observable }, mockCase.id)
);
});

it('invalidates the queries correctly', async () => {
const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries');
const { waitForNextUpdate, result } = renderHook(() => usePostObservable(mockCase.id), {
const { result } = renderHook(() => usePostObservable(mockCase.id), {
wrapper: appMockRender.AppWrapper,
});

act(() => {
result.current.mutate(observableMock);
});

await waitForNextUpdate();

expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.caseView());
await waitFor(() => expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.caseView()));
});

it('does shows a success toaster', async () => {
const { waitForNextUpdate, result } = renderHook(() => usePostObservable(mockCase.id), {
const { result } = renderHook(() => usePostObservable(mockCase.id), {
wrapper: appMockRender.AppWrapper,
});

act(() => {
result.current.mutate(observableMock);
});

await waitForNextUpdate();

expect(addSuccess).toHaveBeenCalled();
await waitFor(() => expect(addSuccess).toHaveBeenCalled());
});

it('shows a toast error when the api return an error', async () => {
jest
.spyOn(api, 'postObservable')
.mockRejectedValue(new Error('usePostObservables: Test error'));

const { waitForNextUpdate, result } = renderHook(() => usePostObservable(mockCase.id), {
const { result } = renderHook(() => usePostObservable(mockCase.id), {
wrapper: appMockRender.AppWrapper,
});

act(() => {
result.current.mutate(observableMock);
});

await waitForNextUpdate();

expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act, waitFor } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../../test_utils';
import { AlertsQueryContext } from '@kbn/alerts-ui-shared/src/common/contexts/alerts_query_context';
import { useBulkUntrackAlertsByQuery } from './use_bulk_untrack_alerts_by_query';
Expand Down Expand Up @@ -35,7 +35,7 @@ describe('useBulkUntrackAlertsByQuery', () => {
it('calls the api when invoked with the correct parameters', async () => {
httpMock.mockResolvedValue(response);

const { result, waitFor } = renderHook(() => useBulkUntrackAlertsByQuery(), {
const { result } = renderHook(() => useBulkUntrackAlertsByQuery(), {
wrapper: appMockRender.AppWrapper,
});

Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/lens/public/app_plugin/app_helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { faker } from '@faker-js/faker';
import { UseNavigateBackToAppProps, useNavigateBackToApp } from './app_helpers';
import { defaultDoc, makeDefaultServices } from '../mocks/services_mock';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import React from 'react';
import { mount } from 'enzyme';
import { HttpStatusBadge } from '.';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useEuiTheme } from '@elastic/eui';

describe('HttpStatusBadge', () => {
Expand Down
Loading

0 comments on commit 1c3f7a6

Please sign in to comment.