Skip to content

Commit

Permalink
[8.x] [React18] Migrate test suites to account for testing library up…
Browse files Browse the repository at this point in the history
…grades kibana-visualizations (#201152) (#201424)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[React18] Migrate test suites to account for testing library upgrades
kibana-visualizations
(#201152)](#201152)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Eyo O.
Eyo","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-11-22T15:34:11Z","message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-visualizations (#201152)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.","sha":"bf1c23b1319de7cd4b80c2b265705b910a48c99f","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Feature:ExpressionLanguage","Team:Visualizations","release_note:skip","v9.0.0","backport:prev-minor","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
kibana-visualizations","number":201152,"url":"https://github.com/elastic/kibana/pull/201152","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-visualizations (#201152)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.","sha":"bf1c23b1319de7cd4b80c2b265705b910a48c99f"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/201152","number":201152,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-visualizations (#201152)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.","sha":"bf1c23b1319de7cd4b80c2b265705b910a48c99f"}}]}] BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 22, 2024
1 parent 722d718 commit 3d3701b
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 3d3701b

Please sign in to comment.