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

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.

---------

Co-authored-by: Elastic Machine <[email protected]>
(cherry picked from commit 691f493)
  • Loading branch information
eokoneyo committed Nov 25, 2024
1 parent d152212 commit 38b9da4
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 38b9da4

Please sign in to comment.