[React18] Migrate test suites to account for testing library upgrades kibana-visualizations (#201152)

This PR migrates test suites that use `renderHook` from the library
`@testing-library/react-hooks` to adopt the equivalent and replacement
of `renderHook` from the export that is now available from
`@testing-library/react`. This work is required for the planned
migration to react18.

##  Context

In this PR, usages of `waitForNextUpdate` that previously could have
been destructured from `renderHook` are now been replaced with `waitFor`
exported from `@testing-library/react`, furthermore `waitFor`
that would also have been destructured from the same renderHook result
is now been replaced with `waitFor` from the export of
`@testing-library/react`.

***Why is `waitFor` a sufficient enough replacement for
`waitForNextUpdate`, and better for testing values subject to async
computations?***

WaitFor will retry the provided callback if an error is returned, till
the configured timeout elapses. By default the retry interval is `50ms`
with a timeout value of `1000ms` that
effectively translates to at least 20 retries for assertions placed
within waitFor. See
https://testing-library.com/docs/dom-testing-library/api-async/#waitfor
for more information.
This however means that for person's writing tests, said person has to
be explicit about expectations that describe the internal state of the
hook being tested.
This implies checking for instance when a react query hook is being
rendered, there's an assertion that said hook isn't loading anymore.

In this PR you'd notice that this pattern has been adopted, with most
existing assertions following an invocation of `waitForNextUpdate` being
placed within a `waitFor`
invocation. In some cases the replacement is simply a `waitFor(() => new
Promise((resolve) => resolve(null)))` (many thanks to @kapral18, for
point out exactly why this works),
where this suffices the assertions that follow aren't placed within a
waitFor so this PR doesn't get larger than it needs to be.

It's also worth pointing out this PR might also contain changes to test
and application code to improve said existing test.

### What to do next?
1. Review the changes in this PR.
2. If you think the changes are correct, approve the PR.

## Any questions?
If you have any questions or need help with this PR, please leave
comments in this PR.
This commit is contained in:
Eyo O. Eyo 2024-11-22 16:34:11 +01:00 committed by GitHub
parent a2d61a4cb6
commit bf1c23b131
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 60 additions and 60 deletions

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useDebouncedValue } from './debounced_value';
describe('useDebouncedValue', () => {

View file

@ -8,7 +8,7 @@
*/
import { TestScheduler } from 'rxjs/testing';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { Chart, PointerEvent } from '@elastic/charts';
import type { Datatable } from '@kbn/expressions-plugin/public';
import type { RefObject } from 'react';

View file

@ -10,8 +10,7 @@
import React from 'react';
import { from } from 'rxjs';
import { take } from 'rxjs';
import { renderHook, act } from '@testing-library/react-hooks';
import { render, act as renderAct } from '@testing-library/react';
import { render, act as renderAct, renderHook, act } from '@testing-library/react';
import { LIGHT_THEME, DARK_THEME } from '@elastic/charts';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useDebouncedValue } from './use_debounced_value';
describe('useDebouncedValue', () => {

View file

@ -8,7 +8,7 @@
*/
import type { RefObject } from 'react';
import { act, renderHook, RenderHookResult } from '@testing-library/react-hooks';
import { renderHook, act, RenderHookResult } from '@testing-library/react';
import { Subject } from 'rxjs';
import type { IInterpreterRenderHandlers } from '../../common';
import { ExpressionRendererParams, useExpressionRenderer } from './use_expression_renderer';
@ -23,7 +23,7 @@ describe('useExpressionRenderer', () => {
loading$: Subject<void>;
render$: Subject<number>;
};
let hook: RenderHookResult<ExpressionRendererParams, ReturnType<typeof useExpressionRenderer>>;
let hook: RenderHookResult<ReturnType<typeof useExpressionRenderer>, ExpressionRendererParams>;
beforeEach(() => {
nodeRef = { current: document.createElement('div') };

View file

@ -7,7 +7,7 @@
* 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 { useShallowMemo } from './use_shallow_memo';
describe('useShallowMemo', () => {

View file

@ -155,7 +155,7 @@ describe('Saved query management list component', () => {
it('should render the saved queries on the selectable component', async () => {
render(wrapSavedQueriesListComponentInContext(props));
expect(await screen.findAllByRole('option')).toHaveLength(1);
await waitFor(() => expect(screen.queryAllByRole('option')).toHaveLength(1));
expect(screen.getByRole('option', { name: 'Test' })).toBeInTheDocument();
});

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { AggTypes } from '../../../common';
import { usePagination } from './use_pagination';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook, act } from '@testing-library/react';
import type { PersistedState } from '@kbn/visualizations-plugin/public';
import { TableVisUiState } from '../../types';
import { useUiState } from './use_ui_state';
@ -39,7 +39,7 @@ describe('useUiState', () => {
});
it('should subscribe on uiState changes and update local state', async () => {
const { result, unmount, waitForNextUpdate } = renderHook(() => useUiState(uiState));
const { result, unmount } = renderHook(() => useUiState(uiState));
expect(uiState.on).toHaveBeenCalledWith('change', expect.any(Function));
// @ts-expect-error
@ -61,18 +61,18 @@ describe('useUiState', () => {
updateOnChange();
});
await waitForNextUpdate();
// should update local state with new values
expect(result.current).toEqual({
columnsWidth: [],
sort: {
columnIndex: 1,
direction: 'asc',
},
setColumnsWidth: expect.any(Function),
setSort: expect.any(Function),
});
await waitFor(() =>
expect(result.current).toEqual({
columnsWidth: [],
sort: {
columnIndex: 1,
direction: 'asc',
},
setColumnsWidth: expect.any(Function),
setSort: expect.any(Function),
})
);
act(() => {
updateOnChange();

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { chromeServiceMock } from '@kbn/core/public/mocks';
import { useChromeVisibility } from './use_chrome_visibility';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { EventEmitter } from 'events';
import { useEditorUpdates } from './use_editor_updates';

View file

@ -7,7 +7,7 @@
* 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 { EventEmitter } from 'events';
import { useLinkedSearchUpdates } from './use_linked_search_updates';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { EventEmitter } from 'events';
import { setTypes } from '../../../services';
@ -127,7 +127,7 @@ describe('useSavedVisInstance', () => {
describe('edit saved visualization route', () => {
test('should load instance and initiate an editor if chrome is set up', async () => {
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useSavedVisInstance(mockServices, eventEmitter, true, undefined, savedVisId)
);
@ -135,7 +135,7 @@ describe('useSavedVisInstance', () => {
expect(mockGetVisualizationInstance).toHaveBeenCalledWith(mockServices, savedVisId);
expect(mockGetVisualizationInstance.mock.calls.length).toBe(1);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(mockServices.chrome.setBreadcrumbs).toHaveBeenCalledWith('Test Vis');
expect(mockServices.chrome.docTitle.change).toHaveBeenCalledWith('Test Vis');
expect(getEditBreadcrumbs).toHaveBeenCalledWith(
@ -156,7 +156,7 @@ describe('useSavedVisInstance', () => {
},
id: 'panel1',
};
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useSavedVisInstance(
mockServices,
eventEmitter,
@ -171,7 +171,7 @@ describe('useSavedVisInstance', () => {
expect(mockGetVisualizationInstance).toHaveBeenCalledWith(mockServices, savedVisId);
expect(mockGetVisualizationInstance.mock.calls.length).toBe(1);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(mockServices.chrome.setBreadcrumbs).toHaveBeenCalledWith('Test Vis');
expect(mockServices.chrome.docTitle.change).toHaveBeenCalledWith('Test Vis');
expect(getEditBreadcrumbs).toHaveBeenCalledWith(
@ -189,13 +189,13 @@ describe('useSavedVisInstance', () => {
});
test('should destroy the editor and the savedVis on unmount if chrome exists', async () => {
const { result, unmount, waitForNextUpdate } = renderHook(() =>
const { result, unmount } = renderHook(() =>
useSavedVisInstance(mockServices, eventEmitter, true, undefined, savedVisId)
);
result.current.visEditorRef.current = document.createElement('div');
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
unmount();
expect(mockDefaultEditorControllerDestroy.mock.calls.length).toBe(1);
@ -215,7 +215,7 @@ describe('useSavedVisInstance', () => {
});
test('should create new visualization based on search params', async () => {
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useSavedVisInstance(mockServices, eventEmitter, true, undefined, undefined)
);
@ -226,7 +226,7 @@ describe('useSavedVisInstance', () => {
type: 'area',
});
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(getCreateBreadcrumbs).toHaveBeenCalled();
expect(mockEmbeddableHandlerRender).not.toHaveBeenCalled();
@ -263,7 +263,7 @@ describe('useSavedVisInstance', () => {
describe('embeded mode', () => {
test('should create new visualization based on search params', async () => {
const { result, unmount, waitForNextUpdate } = renderHook(() =>
const { result, unmount } = renderHook(() =>
useSavedVisInstance(mockServices, eventEmitter, false, undefined, savedVisId)
);
@ -273,7 +273,7 @@ describe('useSavedVisInstance', () => {
expect(mockGetVisualizationInstance).toHaveBeenCalledWith(mockServices, savedVisId);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(mockEmbeddableHandlerRender).toHaveBeenCalled();
expect(result.current.visEditorController).toBeUndefined();

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { EventEmitter } from 'events';
import { Observable } from 'rxjs';
@ -159,11 +159,11 @@ describe('useVisualizeAppState', () => {
it('should successfully update vis state and set up app state container', async () => {
stateContainerGetStateMock.mockImplementation(() => state);
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useVisualizeAppState(mockServices, eventEmitter, savedVisInstance)
);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
const { aggs, ...visState } = stateContainer.getState().vis;
const expectedNewVisState = {
@ -183,11 +183,11 @@ describe('useVisualizeAppState', () => {
...visualizeAppStateStub,
query: { query: 'test', language: 'kuery' },
}));
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useVisualizeAppState(mockServices, eventEmitter, savedVisInstance)
);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
const { aggs, ...visState } = stateContainer.getState().vis;
const expectedNewVisState = {

View file

@ -10,7 +10,7 @@ import { spacesPluginMock } from '@kbn/spaces-plugin/public/mocks';
import { dataPluginMock } from '@kbn/data-plugin/public/mocks';
import { createMockGraphStore } from '../state_management/mocks';
import { Workspace } from '../types';
import { renderHook, act, RenderHookOptions } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { ContentClient } from '@kbn/content-management-plugin/public';
jest.mock('react-router-dom', () => {
@ -51,15 +51,16 @@ describe('use_workspace_loader', () => {
};
it('should not redirect if outcome is exactMatch', async () => {
await act(async () => {
renderHook(
() => useWorkspaceLoader(defaultProps),
defaultProps as RenderHookOptions<UseWorkspaceLoaderProps>
);
renderHook((props) => useWorkspaceLoader(props), {
initialProps: defaultProps,
});
await waitFor(() => {
expect(defaultProps.spaces?.ui.redirectLegacyUrl).not.toHaveBeenCalled();
expect(defaultProps.store.dispatch).toHaveBeenCalled();
});
expect(defaultProps.spaces?.ui.redirectLegacyUrl).not.toHaveBeenCalled();
expect(defaultProps.store.dispatch).toHaveBeenCalled();
});
it('should redirect if outcome is aliasMatch', async () => {
const props = {
...defaultProps,
@ -77,16 +78,16 @@ describe('use_workspace_loader', () => {
},
} as unknown as UseWorkspaceLoaderProps;
await act(async () => {
renderHook(
() => useWorkspaceLoader(props),
props as RenderHookOptions<UseWorkspaceLoaderProps>
);
});
expect(props.spaces?.ui.redirectLegacyUrl).toHaveBeenCalledWith({
path: '#/workspace/aliasTargetId?query={}',
aliasPurpose: 'savedObjectConversion',
objectNoun: 'Graph',
renderHook((_props) => useWorkspaceLoader(_props), {
initialProps: props,
});
await waitFor(() =>
expect(props.spaces?.ui.redirectLegacyUrl).toHaveBeenCalledWith({
path: '#/workspace/aliasTargetId?query={}',
aliasPurpose: 'savedObjectConversion',
objectNoun: 'Graph',
})
);
});
});