mirror of
https://github.com/elastic/kibana.git
synced 2025-04-24 17:59:23 -04:00
# Backport This will backport the following commits from `main` to `8.x`: - [[React18] Migrate test suites to account for testing library upgrades response-ops (#201141)](https://github.com/elastic/kibana/pull/201141) <!--- 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":"7893459+eokoneyo@users.noreply.github.com"},"sourceCommit":{"committedDate":"2024-11-22T16:43:23Z","message":"[React18] Migrate test suites to account for testing library upgrades response-ops (#201141)\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":"3890bde1ab9510adc7b6b8333861d3de51381ef5","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","Team:ResponseOps","v9.0.0","backport:prev-minor","React@18"],"title":"[React18] Migrate test suites to account for testing library upgrades response-ops","number":201141,"url":"https://github.com/elastic/kibana/pull/201141","mergeCommit":{"message":"[React18] Migrate test suites to account for testing library upgrades response-ops (#201141)\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":"3890bde1ab9510adc7b6b8333861d3de51381ef5"}},"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/201141","number":201141,"mergeCommit":{"message":"[React18] Migrate test suites to account for testing library upgrades response-ops (#201141)\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":"3890bde1ab9510adc7b6b8333861d3de51381ef5"}}]}] BACKPORT--> Co-authored-by: Eyo O. Eyo <7893459+eokoneyo@users.noreply.github.com>
415 lines
13 KiB
TypeScript
415 lines
13 KiB
TypeScript
/*
|
|
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
|
|
* or more contributor license agreements. Licensed under the Elastic License
|
|
* 2.0; you may not use this file except in compliance with the Elastic License
|
|
* 2.0.
|
|
*/
|
|
|
|
import { useKibana, useToasts } from './lib/kibana';
|
|
import type { AppMockRenderer } from './mock';
|
|
import { createAppMockRenderer, TestProviders } from './mock';
|
|
import { CaseToastSuccessContent, useCasesToast } from './use_cases_toast';
|
|
import { alertComment, basicComment, mockCase } from '../containers/mock';
|
|
import React from 'react';
|
|
import userEvent from '@testing-library/user-event';
|
|
import type { SupportedCaseAttachment } from '../types';
|
|
import { getByTestId, queryByTestId, screen, renderHook } from '@testing-library/react';
|
|
import { OWNER_INFO } from '../../common/constants';
|
|
import { useApplication } from './lib/kibana/use_application';
|
|
|
|
jest.mock('./lib/kibana');
|
|
jest.mock('./lib/kibana/use_application');
|
|
|
|
const useToastsMock = useToasts as jest.Mock;
|
|
const useKibanaMock = useKibana as jest.Mocked<typeof useKibana>;
|
|
const useApplicationMock = useApplication as jest.Mock;
|
|
|
|
describe('Use cases toast hook', () => {
|
|
const successMock = jest.fn();
|
|
const errorMock = jest.fn();
|
|
const dangerMock = jest.fn();
|
|
const getUrlForApp = jest.fn().mockReturnValue(`/app/cases/${mockCase.id}`);
|
|
const navigateToUrl = jest.fn();
|
|
|
|
function validateTitle(title: string) {
|
|
const mockParams = successMock.mock.calls[0][0];
|
|
const el = document.createElement('div');
|
|
mockParams.title(el);
|
|
expect(el).toHaveTextContent(title);
|
|
}
|
|
|
|
function validateContent(content: string) {
|
|
const mockParams = successMock.mock.calls[0][0];
|
|
const el = document.createElement('div');
|
|
mockParams.text(el);
|
|
expect(el).toHaveTextContent(content);
|
|
}
|
|
|
|
async function navigateToCase() {
|
|
const mockParams = successMock.mock.calls[0][0];
|
|
const el = document.createElement('div');
|
|
mockParams.text(el);
|
|
const button = getByTestId(el, 'toaster-content-case-view-link');
|
|
await userEvent.click(button);
|
|
}
|
|
|
|
useToastsMock.mockImplementation(() => {
|
|
return {
|
|
addSuccess: successMock,
|
|
addError: errorMock,
|
|
addDanger: dangerMock,
|
|
};
|
|
});
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
useKibanaMock().services.application = {
|
|
...useKibanaMock().services.application,
|
|
getUrlForApp,
|
|
navigateToUrl,
|
|
};
|
|
|
|
useApplicationMock.mockReturnValue({ appId: 'testAppId' });
|
|
});
|
|
|
|
describe('showSuccessAttach', () => {
|
|
describe('Toast hook', () => {
|
|
it('should create a success toast when invoked with a case', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({
|
|
theCase: mockCase,
|
|
});
|
|
expect(successMock).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('toast title', () => {
|
|
it('should create a success toast when invoked with a case and a custom title', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({ theCase: mockCase, title: 'Custom title' });
|
|
validateTitle('Custom title');
|
|
});
|
|
|
|
it('should display the alert sync title when called with an alert attachment (1 alert)', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({
|
|
theCase: mockCase,
|
|
attachments: [alertComment as SupportedCaseAttachment],
|
|
});
|
|
validateTitle('An alert was added to "Another horrible breach!!');
|
|
});
|
|
|
|
it('should display the alert sync title when called with an alert attachment (multiple alerts)', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
const alert = {
|
|
...alertComment,
|
|
alertId: ['1234', '54321'],
|
|
} as SupportedCaseAttachment;
|
|
|
|
result.current.showSuccessAttach({
|
|
theCase: mockCase,
|
|
attachments: [alert],
|
|
});
|
|
validateTitle('Alerts were added to "Another horrible breach!!');
|
|
});
|
|
|
|
it('should display a generic title when called with a non-alert attachament', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({
|
|
theCase: mockCase,
|
|
attachments: [basicComment as SupportedCaseAttachment],
|
|
});
|
|
validateTitle('Another horrible breach!! has been updated');
|
|
});
|
|
});
|
|
|
|
describe('Toast content', () => {
|
|
let appMockRender: AppMockRenderer;
|
|
const onViewCaseClick = jest.fn();
|
|
|
|
beforeEach(() => {
|
|
appMockRender = createAppMockRenderer();
|
|
onViewCaseClick.mockReset();
|
|
});
|
|
|
|
it('should create a success toast when invoked with a case and a custom content', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({ theCase: mockCase, content: 'Custom content' });
|
|
validateContent('Custom content');
|
|
});
|
|
|
|
it('renders an alert-specific content when called with an alert attachment and sync on', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({
|
|
theCase: mockCase,
|
|
attachments: [alertComment as SupportedCaseAttachment],
|
|
});
|
|
validateContent('The alert statuses are synched with the case status.');
|
|
});
|
|
|
|
it('renders empty content when called with an alert attachment and sync off', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
result.current.showSuccessAttach({
|
|
theCase: { ...mockCase, settings: { ...mockCase.settings, syncAlerts: false } },
|
|
attachments: [alertComment as SupportedCaseAttachment],
|
|
});
|
|
validateContent('View case');
|
|
});
|
|
|
|
it('renders a correct successful message content', () => {
|
|
const result = appMockRender.render(
|
|
<CaseToastSuccessContent content={'my content'} onViewCaseClick={onViewCaseClick} />
|
|
);
|
|
expect(result.getByTestId('toaster-content-sync-text')).toHaveTextContent('my content');
|
|
expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case');
|
|
expect(onViewCaseClick).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('renders a correct successful message without content', () => {
|
|
const result = appMockRender.render(
|
|
<CaseToastSuccessContent onViewCaseClick={onViewCaseClick} />
|
|
);
|
|
expect(result.queryByTestId('toaster-content-sync-text')).toBeFalsy();
|
|
expect(result.getByTestId('toaster-content-case-view-link')).toHaveTextContent('View case');
|
|
expect(onViewCaseClick).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('Calls the onViewCaseClick when clicked', async () => {
|
|
const result = appMockRender.render(
|
|
<CaseToastSuccessContent onViewCaseClick={onViewCaseClick} />
|
|
);
|
|
|
|
await userEvent.click(result.getByTestId('toaster-content-case-view-link'));
|
|
expect(onViewCaseClick).toHaveBeenCalled();
|
|
});
|
|
|
|
it('hides the view case link when onViewCaseClick is not defined', () => {
|
|
appMockRender.render(<CaseToastSuccessContent />);
|
|
|
|
expect(screen.queryByTestId('toaster-content-case-view-link')).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
describe('Toast navigation', () => {
|
|
const tests = Object.entries(OWNER_INFO).map(([owner, ownerInfo]) => [
|
|
owner,
|
|
ownerInfo.appId,
|
|
]);
|
|
|
|
it.each(tests)(
|
|
'should navigate correctly with owner %s and appId %s',
|
|
async (owner, appId) => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showSuccessAttach({
|
|
theCase: { ...mockCase, owner },
|
|
title: 'Custom title',
|
|
});
|
|
|
|
await navigateToCase();
|
|
|
|
expect(getUrlForApp).toHaveBeenCalledWith(appId, {
|
|
deepLinkId: 'cases',
|
|
path: '/mock-id',
|
|
});
|
|
|
|
expect(navigateToUrl).toHaveBeenCalledWith('/app/cases/mock-id');
|
|
}
|
|
);
|
|
|
|
it('navigates to the current app if the owner is invalid', async () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showSuccessAttach({
|
|
theCase: { ...mockCase, owner: 'in-valid' },
|
|
title: 'Custom title',
|
|
});
|
|
|
|
await navigateToCase();
|
|
|
|
expect(getUrlForApp).toHaveBeenCalledWith('testAppId', {
|
|
deepLinkId: 'cases',
|
|
path: '/mock-id',
|
|
});
|
|
});
|
|
|
|
it('does not navigates to a case if the appId is not defined', () => {
|
|
useApplicationMock.mockReturnValue({ appId: undefined });
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showSuccessAttach({
|
|
theCase: { ...mockCase, owner: 'in-valid' },
|
|
title: 'Custom title',
|
|
});
|
|
|
|
const mockParams = successMock.mock.calls[0][0];
|
|
const el = document.createElement('div');
|
|
mockParams.text(el);
|
|
const button = queryByTestId(el, 'toaster-content-case-view-link');
|
|
|
|
expect(button).toBeNull();
|
|
expect(getUrlForApp).not.toHaveBeenCalled();
|
|
expect(navigateToUrl).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('showErrorToast', () => {
|
|
it('should show an error toast', () => {
|
|
const error = new Error('showErrorToast: an error occurred');
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showErrorToast(error);
|
|
|
|
expect(errorMock).toHaveBeenCalledWith(error, { title: error.message });
|
|
});
|
|
|
|
it('should override the title', () => {
|
|
const error = new Error('showErrorToast: an error occurred');
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showErrorToast(error, { title: 'my title' });
|
|
|
|
expect(errorMock).toHaveBeenCalledWith(error, { title: 'my title' });
|
|
});
|
|
|
|
it('should not show an error toast if the error is AbortError', () => {
|
|
const error = new Error('showErrorToast: an error occurred');
|
|
error.name = 'AbortError';
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showErrorToast(error);
|
|
|
|
expect(errorMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('should show the body message if it is a ServerError', () => {
|
|
const error = new Error('showErrorToast: an error occurred');
|
|
// @ts-expect-error: need to create a ServerError
|
|
error.body = { message: 'message error' };
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showErrorToast(error);
|
|
|
|
expect(errorMock).toHaveBeenCalledWith(new Error('message error'), {
|
|
title: 'message error',
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('showSuccessToast', () => {
|
|
it('should show a success toast', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showSuccessToast('my title');
|
|
|
|
expect(successMock).toHaveBeenCalledWith({
|
|
className: 'eui-textBreakWord',
|
|
title: 'my title',
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('showDangerToast', () => {
|
|
it('should show a danger toast', () => {
|
|
const { result } = renderHook(
|
|
() => {
|
|
return useCasesToast();
|
|
},
|
|
{ wrapper: TestProviders }
|
|
);
|
|
|
|
result.current.showDangerToast('my danger toast');
|
|
|
|
expect(dangerMock).toHaveBeenCalledWith({
|
|
className: 'eui-textBreakWord',
|
|
title: 'my danger toast',
|
|
});
|
|
});
|
|
});
|
|
});
|