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 obs-ux-infra_services-team (#201168) (#201608)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[React18] Migrate test suites to account for testing library upgrades
obs-ux-infra_services-team
(#201168)](#201168)

<!--- 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-25T14:18:14Z","message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-infra_services-team (#201168)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"691f493cd4a8adeddc6a6eb8df626c948f0c5e02","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","backport:prev-minor","ci:project-deploy-observability","Team:obs-ux-infra_services","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-infra_services-team","number":201168,"url":"https://github.com/elastic/kibana/pull/201168","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-infra_services-team (#201168)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"691f493cd4a8adeddc6a6eb8df626c948f0c5e02"}},"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/201168","number":201168,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-infra_services-team (#201168)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"691f493cd4a8adeddc6a6eb8df626c948f0c5e02"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 25, 2024
1 parent 5d9b7fa commit 874d6df
Show file tree
Hide file tree
Showing 36 changed files with 394 additions and 312 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
* 2.0.
*/

import React, { ReactNode } from 'react';
import React, { PropsWithChildren } from 'react';
import { merge } from 'lodash';
import { createMemoryHistory } from 'history';
import { renderHook, act } from '@testing-library/react-hooks';

import { act, waitFor, renderHook } from '@testing-library/react';

import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context';
import {
Expand All @@ -22,7 +23,7 @@ import { fromQuery } from '../../shared/links/url_helpers';
import { useFailedTransactionsCorrelations } from './use_failed_transactions_correlations';
import type { APIEndpoint } from '../../../../server';

function wrapper({ children, error = false }: { children?: ReactNode; error: boolean }) {
function wrapper({ children, error = false }: PropsWithChildren<{ error?: boolean }>) {
const getHttpMethodMock = (method: 'GET' | 'POST') =>
jest.fn().mockImplementation(async (pathname) => {
await delay(100);
Expand Down Expand Up @@ -107,39 +108,40 @@ describe('useFailedTransactionsCorrelations', () => {
wrapper,
});

try {
await waitFor(() =>
expect(result.current.progress).toEqual({
isRunning: true,
loaded: 0,
});
expect(result.current.response).toEqual({ ccsWarning: false });
expect(typeof result.current.startFetch).toEqual('function');
expect(typeof result.current.cancelFetch).toEqual('function');
} finally {
unmount();
}
})
);

expect(result.current.response).toEqual({ ccsWarning: false });
expect(result.current.startFetch).toEqual(expect.any(Function));
expect(result.current.cancelFetch).toEqual(expect.any(Function));

unmount();
});

it('should not have received any results after 50ms', async () => {
const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
});

try {
jest.advanceTimersByTime(50);
jest.advanceTimersByTime(50);

await waitFor(() =>
expect(result.current.progress).toEqual({
isRunning: true,
loaded: 0,
});
expect(result.current.response).toEqual({ ccsWarning: false });
} finally {
unmount();
}
})
);

expect(result.current.response).toEqual({ ccsWarning: false });
unmount();
});

it('should receive partial updates and finish running', async () => {
const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), {
const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
});

Expand Down Expand Up @@ -253,29 +255,37 @@ describe('useFailedTransactionsCorrelations', () => {
});
describe('when throwing an error', () => {
it('should automatically start fetching results', async () => {
const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useFailedTransactionsCorrelations, {
wrapper: ({ children }) =>
React.createElement(
wrapper,
{
error: true,
},
children
),
});

try {
await waitFor(() =>
expect(result.current.progress).toEqual({
isRunning: true,
loaded: 0,
});
} finally {
unmount();
}
})
);

unmount();
});

it('should still be running after 50ms', async () => {
const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useFailedTransactionsCorrelations, {
wrapper: ({ children }) =>
React.createElement(
wrapper,
{
error: true,
},
children
),
});

try {
Expand All @@ -292,11 +302,15 @@ describe('useFailedTransactionsCorrelations', () => {
});

it('should stop and return an error after more than 100ms', async () => {
const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useFailedTransactionsCorrelations, {
wrapper: ({ children }) =>
React.createElement(
wrapper,
{
error: true,
},
children
),
});

try {
Expand All @@ -316,7 +330,7 @@ describe('useFailedTransactionsCorrelations', () => {

describe('when canceled', () => {
it('should stop running', async () => {
const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), {
const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), {
wrapper,
});

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

import React, { ReactNode } from 'react';
import React, { PropsWithChildren } from 'react';
import { merge } from 'lodash';
import { createMemoryHistory } from 'history';
import { renderHook, act } from '@testing-library/react-hooks';

import { act, waitFor, renderHook } from '@testing-library/react';

import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context';
import {
Expand All @@ -22,7 +23,7 @@ import { fromQuery } from '../../shared/links/url_helpers';
import { useLatencyCorrelations } from './use_latency_correlations';
import type { APIEndpoint } from '../../../../server';

function wrapper({ children, error = false }: { children?: ReactNode; error: boolean }) {
function wrapper({ children, error = false }: PropsWithChildren<{ error?: boolean }>) {
const getHttpMethodMock = (method: 'GET' | 'POST') =>
jest.fn().mockImplementation(async (pathname) => {
await delay(100);
Expand Down Expand Up @@ -86,16 +87,17 @@ function wrapper({ children, error = false }: { children?: ReactNode; error: boo
}

describe('useLatencyCorrelations', () => {
beforeEach(async () => {
jest.useFakeTimers({ legacyFakeTimers: true });
});
afterEach(() => {
jest.useRealTimers();
});

describe('when successfully loading results', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('should automatically start fetching results', async () => {
const { result, unmount } = renderHook(() => useLatencyCorrelations(), {
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper,
});

Expand All @@ -113,7 +115,7 @@ describe('useLatencyCorrelations', () => {
});

it('should not have received any results after 50ms', async () => {
const { result, unmount } = renderHook(() => useLatencyCorrelations(), {
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper,
});

Expand All @@ -131,7 +133,7 @@ describe('useLatencyCorrelations', () => {
});

it('should receive partial updates and finish running', async () => {
const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), {
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper,
});

Expand Down Expand Up @@ -213,12 +215,17 @@ describe('useLatencyCorrelations', () => {
});

describe('when throwing an error', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('should automatically start fetching results', async () => {
const { result, unmount } = renderHook(() => useLatencyCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper: ({ children }) => wrapper({ children, error: true }),
});

try {
Expand All @@ -232,11 +239,8 @@ describe('useLatencyCorrelations', () => {
});

it('should still be running after 50ms', async () => {
const { result, unmount } = renderHook(() => useLatencyCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper: ({ children }) => wrapper({ children, error: true }),
});

try {
Expand All @@ -253,31 +257,38 @@ describe('useLatencyCorrelations', () => {
});

it('should stop and return an error after more than 100ms', async () => {
const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), {
wrapper,
initialProps: {
error: true,
},
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper: ({ children }) => wrapper({ children, error: true }),
});

try {
jest.advanceTimersByTime(150);
await waitFor(() => expect(result.current.progress.error).toBeDefined());

expect(result.current.progress).toEqual({
error: 'Something went wrong',
isRunning: false,
loaded: 0,
act(() => {
jest.advanceTimersByTime(150);
});
await waitFor(() =>
expect(result.current.progress).toEqual({
error: 'Something went wrong',
isRunning: false,
loaded: 0,
})
);
} finally {
unmount();
}
});
});

describe('when canceled', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('should stop running', async () => {
const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), {
const { result, unmount } = renderHook(useLatencyCorrelations, {
wrapper,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/
import React, { ReactNode } from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useTabs } from './use_tabs';
import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public';
import { CoreStart } from '@kbn/core/public';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ describe('EmptyBanner', () => {
it('does not render null', async () => {
const component = renderWithTheme(<EmptyBanner />, { wrapper });

await act(async () => {
act(() => {
cy.add({ data: { id: 'test id' } });
await waitFor(() => {
expect(component.container.children.length).toBeGreaterThan(0);
});
});

await waitFor(() => {
expect(component.container.children.length).toBeGreaterThan(0);
});
});
});
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 cytoscape from 'cytoscape';
import dagre from 'cytoscape-dagre';
import { EuiTheme } from '@kbn/kibana-react-plugin/common';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, render, waitFor } from '@testing-library/react';
import { render, waitFor } from '@testing-library/react';
import { shallow } from 'enzyme';
import React, { ReactNode } from 'react';
import { MemoryRouter } from 'react-router-dom';
Expand Down Expand Up @@ -67,12 +67,9 @@ describe('TraceLink', () => {
},
});

let result;
act(() => {
const component = render(<TraceLink />, renderOptions);
const component = render(<TraceLink />, renderOptions);

result = component.getByText('Fetching trace...');
});
const result = component.getByText('Fetching trace...');
await waitFor(() => {});
expect(result).toBeDefined();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { CoreStart } from '@kbn/core/public';
import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { createMemoryHistory } from 'history';
import React, { ReactNode } from 'react';
import { ServerlessType } from '../../../../../common/serverless';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
* 2.0.
*/

import { fireEvent } from '@testing-library/react';
import { act } from '@testing-library/react-hooks';
import { fireEvent, act } from '@testing-library/react';
import React, { ReactNode } from 'react';
import { MemoryRouter } from 'react-router-dom';
import { MockApmPluginContextWrapper } from '../../../../../context/apm_plugin/mock_apm_plugin_context';
Expand Down
Loading

0 comments on commit 874d6df

Please sign in to comment.