Skip to content

Commit

Permalink
[React18] Migrate test suites to account for testing library upgrades…
Browse files Browse the repository at this point in the history
… 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.
  • Loading branch information
eokoneyo authored Nov 22, 2024
1 parent a2d61a4 commit bf1c23b
Show file tree
Hide file tree
Showing 15 changed files with 60 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
3 changes: 1 addition & 2 deletions src/plugins/charts/public/services/theme/theme.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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') };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
26 changes: 13 additions & 13 deletions src/plugins/vis_types/table/public/utils/use/use_ui_state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -127,15 +127,15 @@ 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)
);

result.current.visEditorRef.current = document.createElement('div');
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(
Expand All @@ -156,7 +156,7 @@ describe('useSavedVisInstance', () => {
},
id: 'panel1',
};
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useSavedVisInstance(
mockServices,
eventEmitter,
Expand All @@ -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(
Expand All @@ -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);
Expand All @@ -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)
);

Expand All @@ -226,7 +226,7 @@ describe('useSavedVisInstance', () => {
type: 'area',
});

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(getCreateBreadcrumbs).toHaveBeenCalled();
expect(mockEmbeddableHandlerRender).not.toHaveBeenCalled();
Expand Down Expand Up @@ -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)
);

Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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 = {
Expand All @@ -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 = {
Expand Down
37 changes: 19 additions & 18 deletions x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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,
Expand All @@ -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',
})
);
});
});

0 comments on commit bf1c23b

Please sign in to comment.