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-security (#201151) (#202144)

# Backport

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

<!--- 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-28T11:11:47Z","message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-security (#201151)\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\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f0540977af8b552cf9eae747c04cf37f3e01c742","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Team:Security","release_note:skip","v9.0.0","backport:prev-minor","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
kibana-security","number":201151,"url":"https://github.com/elastic/kibana/pull/201151","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-security (#201151)\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\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f0540977af8b552cf9eae747c04cf37f3e01c742"}},"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/201151","number":201151,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-security (#201151)\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\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f0540977af8b552cf9eae747c04cf37f3e01c742"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 28, 2024
1 parent 4e73cb1 commit defbb8b
Show file tree
Hide file tree
Showing 9 changed files with 41 additions and 43 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, type WrapperComponent } from '@testing-library/react-hooks';
import { act, renderHook, waitFor } from '@testing-library/react';
import React from 'react';
import { BehaviorSubject, first, lastValueFrom, of } from 'rxjs';

Expand Down Expand Up @@ -35,7 +35,7 @@ const security = {

const { http, notifications } = core;

const wrapper: WrapperComponent<React.PropsWithChildren<{}>> = ({ children }) => (
const wrapper = ({ children }: React.PropsWithChildren<unknown>) => (
<UserProfilesKibanaProvider
core={core}
security={security}
Expand Down Expand Up @@ -78,7 +78,7 @@ describe('useUpdateUserProfile() hook', () => {
await lastValueFrom(updateDone.pipe(first((v) => v === true)));
});

const { result, waitForNextUpdate } = renderHook(() => useUpdateUserProfile(), { wrapper });
const { result } = renderHook(() => useUpdateUserProfile(), { wrapper });
const { update } = result.current;

expect(result.current.isLoading).toBeFalsy();
Expand All @@ -90,9 +90,7 @@ describe('useUpdateUserProfile() hook', () => {
expect(result.current.isLoading).toBeTruthy();

updateDone.next(true); // Resolve the http.post promise
await waitForNextUpdate();

expect(result.current.isLoading).toBeFalsy();
await waitFor(() => expect(result.current.isLoading).toBeFalsy());
});

test('should show a success notification by default', async () => {
Expand All @@ -118,7 +116,9 @@ describe('useUpdateUserProfile() hook', () => {
return true;
};

const { result } = renderHook(() => useUpdateUserProfile({ pageReloadChecker }), { wrapper });
const { result } = renderHook(() => useUpdateUserProfile({ pageReloadChecker }), {
wrapper,
});
const { update } = result.current;

await act(async () => {
Expand Down Expand Up @@ -146,7 +146,9 @@ describe('useUpdateUserProfile() hook', () => {
userProfile$: of(initialValue),
};

const { result } = renderHook(() => useUpdateUserProfile({ pageReloadChecker }), { wrapper });
const { result } = renderHook(() => useUpdateUserProfile({ pageReloadChecker }), {
wrapper,
});
const { update } = result.current;

const nextValue = { userSettings: { darkMode: 'light' as const } };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

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

import type { RevertFunction } from './form_changes';
import { useFormChanges } from './form_changes';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,14 @@ describe('Tags', () => {
};

beforeEach(() => {
jest.clearAllMocks();
useGetTagsMock.mockReturnValue({ data: ['test'] });
appMockRender = createAppMockRenderer();
});

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

it('it renders', async () => {
appMockRender.render(
<MockHookWrapperComponent>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { act, renderHook } from '@testing-library/react';
import { mount } from 'enzyme';
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
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 React from 'react';

import { coreMock } from '@kbn/core/public/mocks';
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 React from 'react';

import { coreMock } from '@kbn/core/public/mocks';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ describe('EditSpaceContentTab', () => {
</TestComponent>
);

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

expect(getSpaceContentSpy).toHaveBeenCalledTimes(1);
expect(getSpaceContentSpy).toHaveBeenCalledWith(space.id);
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 type { PropsWithChildren } from 'react';
import React from 'react';

Expand Down Expand Up @@ -88,10 +88,8 @@ describe('EditSpaceProvider', () => {
});

it('throws when the hook is used within a tree that does not have the provider', () => {
const { result } = renderHook(useEditSpaceServices);
expect(result.error).toBeDefined();
expect(result.error?.message).toEqual(
expect.stringMatching('EditSpaceService Context is missing.')
expect(() => renderHook(useEditSpaceServices)).toThrow(
/EditSpaceService Context is missing./
);
});
});
Expand All @@ -109,12 +107,7 @@ describe('EditSpaceProvider', () => {
});

it('throws when the hook is used within a tree that does not have the provider', () => {
const { result } = renderHook(useEditSpaceStore);

expect(result.error).toBeDefined();
expect(result.error?.message).toEqual(
expect.stringMatching('EditSpaceStore Context is missing.')
);
expect(() => renderHook(useEditSpaceStore)).toThrow(/EditSpaceStore Context is missing./);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ describe('PrivilegesRolesForm', () => {

renderPrivilegeRolesForm();

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

['all', 'read', 'custom'].forEach((privilege) => {
expect(screen.queryByTestId(`${privilege}-privilege-button`)).not.toBeInTheDocument();
Expand All @@ -174,9 +174,9 @@ describe('PrivilegesRolesForm', () => {

renderPrivilegeRolesForm();

await waitFor(() => null);

expect(screen.getByTestId('space-assign-role-create-roles-privilege-button')).toBeDisabled();
await waitFor(() =>
expect(screen.getByTestId('space-assign-role-create-roles-privilege-button')).toBeDisabled()
);
});

it('makes a request to refetch available roles if page transitions back from a user interaction page visibility change', () => {
Expand Down Expand Up @@ -208,7 +208,7 @@ describe('PrivilegesRolesForm', () => {
preSelectedRoles: roles,
});

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

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_READ}-privilege-button`)).toHaveAttribute(
'aria-pressed',
Expand All @@ -234,11 +234,11 @@ describe('PrivilegesRolesForm', () => {
],
});

await waitFor(() => null);

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_ALL}-privilege-button`)).toHaveAttribute(
'aria-pressed',
String(true)
await waitFor(() =>
expect(screen.getByTestId(`${FEATURE_PRIVILEGES_ALL}-privilege-button`)).toHaveAttribute(
'aria-pressed',
String(true)
)
);
});

Expand All @@ -256,7 +256,7 @@ describe('PrivilegesRolesForm', () => {
preSelectedRoles: roles,
});

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

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_READ}-privilege-button`)).toHaveAttribute(
'aria-pressed',
Expand Down Expand Up @@ -290,9 +290,9 @@ describe('PrivilegesRolesForm', () => {
preSelectedRoles: roles,
});

await waitFor(() => null);

expect(screen.getByTestId('privilege-conflict-callout')).toBeInTheDocument();
await waitFor(() =>
expect(screen.getByTestId('privilege-conflict-callout')).toBeInTheDocument()
);
});

it('does not display the permission conflict message when roles with the same privilege levels are selected', async () => {
Expand All @@ -312,9 +312,9 @@ describe('PrivilegesRolesForm', () => {
preSelectedRoles: roles,
});

await waitFor(() => null);

expect(screen.queryByTestId('privilege-conflict-callout')).not.toBeInTheDocument();
await waitFor(() =>
expect(screen.queryByTestId('privilege-conflict-callout')).not.toBeInTheDocument()
);
});
});

Expand Down Expand Up @@ -348,7 +348,7 @@ describe('PrivilegesRolesForm', () => {
preSelectedRoles: roles,
});

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

await userEvent.click(screen.getByTestId('custom-privilege-button'));

Expand Down

0 comments on commit defbb8b

Please sign in to comment.