mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-25 09:40:59 +00:00
Compare commits
3 Commits
ci/goci-go
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af3fd93339 | ||
|
|
22a65c4f74 | ||
|
|
fa1dbe25cb |
@@ -9,7 +9,7 @@ paths:
|
||||
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
|
||||
|
||||
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
|
||||
@@ -552,6 +552,7 @@
|
||||
],
|
||||
"rules": {
|
||||
"import/first": "off",
|
||||
"signoz/no-dom-node-access": "error",
|
||||
// Should ignore due to mocks
|
||||
"signoz/no-navigator-clipboard": "off",
|
||||
// Tests can use navigator.clipboard directly,
|
||||
|
||||
@@ -176,6 +176,7 @@ const preview: Preview = {
|
||||
'AI Observability',
|
||||
['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
|
||||
'Noz',
|
||||
['Overview', 'Modal', 'Panel'],
|
||||
'Metering',
|
||||
['Cost Meter', 'Usage Explorer'],
|
||||
'Messaging Queues',
|
||||
|
||||
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const message = (name) =>
|
||||
`Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`;
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-dom-node-access',
|
||||
valid: [
|
||||
{
|
||||
name: 'Testing Library queries',
|
||||
code: "within(screen.getByTestId('row')).getByText('Name');",
|
||||
},
|
||||
{
|
||||
name: 'a query method that is not called',
|
||||
code:
|
||||
'jest.spyOn(document, "querySelector");\nconst q = Element.prototype.closest;',
|
||||
},
|
||||
{
|
||||
name: 'computed access',
|
||||
code: "const name = 'closest';\nel[name]('tr');",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'querySelector on the container',
|
||||
code: "container.querySelector('.row');",
|
||||
errors: [{ message: message('querySelector'), line: 1, column: 11 }],
|
||||
},
|
||||
{
|
||||
name: 'closest after a screen query',
|
||||
code: "screen.getByText('Name').closest('tr');",
|
||||
errors: [{ message: message('closest'), line: 1, column: 26 }],
|
||||
},
|
||||
{
|
||||
name: 'optional call',
|
||||
code: "row?.querySelectorAll('td');",
|
||||
errors: [{ message: message('querySelectorAll'), line: 1, column: 6 }],
|
||||
},
|
||||
{
|
||||
name: 'traversal property',
|
||||
code: 'expect(cell.parentElement).toBeVisible();',
|
||||
errors: [{ message: message('parentElement'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a DOM node',
|
||||
code: "expect(screen.getByTestId('list').children).toHaveLength(2);",
|
||||
errors: [{ message: message('children'), line: 1, column: 35 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a data tree',
|
||||
code: 'expect(tree.children).toHaveLength(2);',
|
||||
errors: [{ message: message('children'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'document lookup by id',
|
||||
code: "document.getElementById('root');",
|
||||
errors: [{ message: message('getElementById'), line: 1, column: 10 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Rule: no-dom-node-access
|
||||
*
|
||||
* Tests find elements through Testing Library (`screen`, `within`), not by
|
||||
* walking the DOM. Flags calls to DOM query methods and reads of node
|
||||
* traversal properties:
|
||||
* container.querySelector('.row')
|
||||
* screen.getByText('Name').closest('tr')
|
||||
* cell.parentElement
|
||||
* list.children
|
||||
*
|
||||
* A non-DOM `children` read (a data tree, React props) disables the rule on
|
||||
* that line with a reason.
|
||||
*/
|
||||
|
||||
const QUERY_METHODS = new Set([
|
||||
'querySelector',
|
||||
'querySelectorAll',
|
||||
'closest',
|
||||
'getElementById',
|
||||
'getElementsByClassName',
|
||||
'getElementsByTagName',
|
||||
'getElementsByName',
|
||||
]);
|
||||
|
||||
const TRAVERSAL_PROPERTIES = new Set([
|
||||
'parentElement',
|
||||
'parentNode',
|
||||
'firstChild',
|
||||
'lastChild',
|
||||
'firstElementChild',
|
||||
'lastElementChild',
|
||||
'nextSibling',
|
||||
'previousSibling',
|
||||
'nextElementSibling',
|
||||
'previousElementSibling',
|
||||
'childNodes',
|
||||
'children',
|
||||
]);
|
||||
|
||||
export default {
|
||||
create(context) {
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
if (node.computed || node.property.type !== 'Identifier') {
|
||||
return;
|
||||
}
|
||||
const { name } = node.property;
|
||||
const isCall =
|
||||
node.parent?.type === 'CallExpression' && node.parent.callee === node;
|
||||
if ((isCall && QUERY_METHODS.has(name)) || TRAVERSAL_PROPERTIES.has(name)) {
|
||||
context.report({
|
||||
node: node.property,
|
||||
message: `Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
|
||||
import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
|
||||
import noTextCss from './rules/no-text-css.mjs';
|
||||
import requireDisableReason from './rules/require-disable-reason.mjs';
|
||||
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -39,5 +40,6 @@ export default {
|
||||
'no-direct-react-router-import': noDirectReactRouterImport,
|
||||
'no-text-css': noTextCss,
|
||||
'require-disable-reason': requireDisableReason,
|
||||
'no-dom-node-access': noDomNodeAccess,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,13 +17,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -15,13 +15,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
|
||||
import LabelColumn from './LabelColumn';
|
||||
|
||||
@@ -92,7 +92,9 @@ describe('LabelColumn', () => {
|
||||
renderWithProviders(<LabelColumn labels={labels} />);
|
||||
|
||||
const isHidden = (label: string): boolean =>
|
||||
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
|
||||
screen
|
||||
.getByTestId(`label-tag-container-${label}`)
|
||||
.classList.contains('overflowed');
|
||||
|
||||
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
|
||||
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
|
||||
@@ -157,8 +159,7 @@ describe('LabelColumn', () => {
|
||||
it('should render empty when no labels provided', () => {
|
||||
renderWithProviders(<LabelColumn labels={[]} />);
|
||||
|
||||
const column = screen.getByTestId('label-column');
|
||||
expect(column.children).toHaveLength(0);
|
||||
expect(screen.getByTestId('label-column')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('should use primary color by default', () => {
|
||||
|
||||
@@ -45,7 +45,7 @@ function LabelTag({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<span className={className}>
|
||||
<span className={className} data-testid={`label-tag-container-${label}`}>
|
||||
<Badge
|
||||
textTransform="none"
|
||||
color={color ?? 'secondary'}
|
||||
|
||||
@@ -22,7 +22,10 @@ function AppLoading(): JSX.Element {
|
||||
const isDarkMode = getThemeFromStorage();
|
||||
|
||||
return (
|
||||
<div className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}>
|
||||
<div
|
||||
className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}
|
||||
data-testid="app-loading-container"
|
||||
>
|
||||
<div className="perilin-bg" />
|
||||
<div className="app-loading-content">
|
||||
<div className="brand">
|
||||
@@ -53,7 +56,7 @@ function AppLoading(): JSX.Element {
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="loader" />
|
||||
<div className="loader" data-testid="app-loading-loader" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { screen } from 'tests/test-utils';
|
||||
|
||||
import getLocal from '../../../api/browser/localstorage/get';
|
||||
import AppLoading from '../AppLoading';
|
||||
@@ -15,7 +16,6 @@ describe('AppLoading', () => {
|
||||
const SIGNOZ_TEXT = 'SigNoz';
|
||||
const TAGLINE_TEXT =
|
||||
'OpenTelemetry-Native Logs, Metrics and Traces in a single pane';
|
||||
const CONTAINER_SELECTOR = '.app-loading-container';
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -33,7 +33,7 @@ describe('AppLoading', () => {
|
||||
expect(screen.getByText(TAGLINE_TEXT)).toBeInTheDocument();
|
||||
|
||||
// Check if dark theme class is applied
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
expect(container).not.toHaveClass('lightMode');
|
||||
});
|
||||
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
|
||||
expect(tagline).toBeInTheDocument();
|
||||
|
||||
// Check for loader
|
||||
const loader = document.querySelector('.loader');
|
||||
const loader = screen.getByTestId('app-loading-loader');
|
||||
expect(loader).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -72,7 +72,7 @@ describe('AppLoading', () => {
|
||||
|
||||
// Should still render with dark theme as fallback
|
||||
expect(screen.getByText(SIGNOZ_TEXT)).toBeInTheDocument();
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('submit button becomes disabled after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -86,7 +86,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('successful submit shows toast.success and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -112,7 +112,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('pressing Enter again while creating sends one request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requests = 0;
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -146,7 +146,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows toast.error on API error and keeps modal open', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -186,7 +186,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('Cancel button closes modal without submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const cancelBtn = await screen.findByTestId('create-sa-cancel-btn');
|
||||
@@ -217,7 +217,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('keeps the footer usable when create permission is denied', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderModal();
|
||||
@@ -242,7 +242,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows "Name is required" after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { fireEvent, screen, userEvent } from 'tests/test-utils';
|
||||
import dayjs from 'dayjs';
|
||||
import { mockAppLocation } from 'tests/router-mocks';
|
||||
import * as timeUtils from 'utils/timeUtils';
|
||||
@@ -157,7 +158,8 @@ describe('CustomTimePicker', () => {
|
||||
expect(onValid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats close after change like pressing Enter (blur + chevron)', () => {
|
||||
it('treats close after change like pressing Enter (blur + chevron)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onValid = jest.fn();
|
||||
const onError = jest.fn();
|
||||
|
||||
@@ -166,16 +168,13 @@ describe('CustomTimePicker', () => {
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Open and change value so "changed since open" is true
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: '5m' } });
|
||||
fireEvent.blur(input);
|
||||
await user.click(input);
|
||||
await user.clear(input);
|
||||
await user.type(input, '5m');
|
||||
await user.tab();
|
||||
|
||||
// Click the chevron (which triggers handleClose)
|
||||
const chevron = document.querySelector(
|
||||
'.time-input-suffix-icon-badge',
|
||||
) as HTMLElement;
|
||||
|
||||
fireEvent.click(chevron);
|
||||
await user.click(screen.getByTestId('time-picker-close-chevron'));
|
||||
|
||||
// Should have applied the value (same as Enter)
|
||||
expect(onValid).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -640,12 +640,14 @@ function CustomTimePicker({
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleClose}
|
||||
data-testid="time-picker-close-chevron"
|
||||
/>
|
||||
) : (
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleOpen}
|
||||
data-testid="time-picker-open-chevron"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -273,7 +273,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('enables Save after editing name and calls updateUser on confirm', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
@@ -306,7 +306,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('does not close the drawer after a successful save', async () => {
|
||||
const onClose = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
|
||||
@@ -331,7 +331,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('adding a new role creates a user role without removing existing ones', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockSet = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useCreateUserRole as jest.Mock).mockReturnValue({
|
||||
@@ -365,7 +365,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('deselecting a role deletes the user role by its assignment id', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
@@ -392,7 +392,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('shows delete confirm dialog and calls deleteUser for active members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -553,7 +553,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls deleteUser after confirming revoke invite for invited members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -583,7 +583,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls updateUser when saving name change for an invited member', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useGetUser as jest.Mock).mockReturnValue({
|
||||
@@ -641,7 +641,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows SaveErrorItem when updateUser fails for name change', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
mutateAsync: jest.fn().mockRejectedValue(new Error('server error')),
|
||||
@@ -669,7 +669,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for active member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -700,7 +700,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for invited member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -740,7 +740,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (isSelf)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -811,7 +811,7 @@ describe('EditMemberDrawer', () => {
|
||||
isLoading: false,
|
||||
});
|
||||
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
const input = await screen.findByDisplayValue('Alice Smith');
|
||||
@@ -875,7 +875,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -886,7 +886,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not call createResetPasswordToken when Reset Link is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(
|
||||
@@ -903,7 +903,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('calls POST and opens the reset link dialog with the generated link and expiry', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -925,7 +925,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
|
||||
|
||||
// Click the close button
|
||||
const closeButton = screen.getByTestId('close-button');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(closeButton);
|
||||
|
||||
// Check if onClose was called
|
||||
@@ -145,7 +145,7 @@ it('should open the modal when the trigger component is clicked', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('Open Error Modal');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
// Check if the modal is displayed
|
||||
@@ -165,12 +165,13 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('error');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('An error occurred')).toBeInTheDocument();
|
||||
});
|
||||
const modal = screen.getByRole('dialog');
|
||||
|
||||
// Trigger the onCancel event
|
||||
await user.click(screen.getByTestId('close-button'));
|
||||
@@ -180,8 +181,6 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// check if the modal is not visible
|
||||
const modal = document.getElementsByClassName('ant-modal');
|
||||
const style = window.getComputedStyle(modal[0]);
|
||||
expect(style.display).toBe('none');
|
||||
expect(modal).toHaveStyle({ display: 'none' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider } from 'react-redux';
|
||||
import { act, render, renderHook } from '@testing-library/react';
|
||||
import { act, render, renderHook } from 'tests/test-utils';
|
||||
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
|
||||
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
|
||||
import { useGlobalTimeStore } from 'store/globalTime/globalTimeStore';
|
||||
@@ -42,13 +42,13 @@ describe('GlobalTimeStoreAdapter', () => {
|
||||
globalTime: createGlobalTimeState(),
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<Provider store={store}>
|
||||
<GlobalTimeStoreAdapter />
|
||||
</Provider>,
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(asFragment().hasChildNodes()).toBe(false);
|
||||
});
|
||||
|
||||
it('should sync relative time from Redux to Zustand store', () => {
|
||||
|
||||
@@ -2,8 +2,14 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
function AnnouncementsModal(): JSX.Element {
|
||||
return (
|
||||
<div className="announcements-modal-container">
|
||||
<div className="announcements-modal-container-header">
|
||||
<div
|
||||
className="announcements-modal-container"
|
||||
data-testid="announcements-modal"
|
||||
>
|
||||
<div
|
||||
className="announcements-modal-container-header"
|
||||
data-testid="announcements-modal-header"
|
||||
>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import AnnouncementsModal from '../AnnouncementsModal';
|
||||
|
||||
@@ -12,15 +12,14 @@ describe('AnnouncementsModal', () => {
|
||||
it('should have proper structure and classes', () => {
|
||||
render(<AnnouncementsModal />);
|
||||
|
||||
const container = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container');
|
||||
expect(container).toBeInTheDocument();
|
||||
const container = screen.getByTestId('announcements-modal');
|
||||
expect(container).toHaveClass('announcements-modal-container');
|
||||
|
||||
const headerContainer = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container-header');
|
||||
expect(headerContainer).toBeInTheDocument();
|
||||
const headerContainer = within(container).getByTestId(
|
||||
'announcements-modal-header',
|
||||
);
|
||||
expect(headerContainer).toHaveClass('announcements-modal-container-header');
|
||||
expect(headerContainer).toHaveTextContent('Announcements');
|
||||
});
|
||||
|
||||
it('should render without any errors', () => {
|
||||
|
||||
@@ -64,7 +64,10 @@ function InviteMembers({
|
||||
const hasSuccesses = successResults.length > 0;
|
||||
|
||||
return (
|
||||
<div className={cx(styles.inviteMembers, className)}>
|
||||
<div
|
||||
className={cx(styles.inviteMembers, className)}
|
||||
data-testid="invite-members"
|
||||
>
|
||||
<div className={styles.table}>
|
||||
{showHeader && (
|
||||
<div className={styles.header}>
|
||||
|
||||
@@ -66,9 +66,9 @@ describe('InviteMembers - Rendering', () => {
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<InviteMembers className="custom-class" />);
|
||||
render(<InviteMembers className="custom-class" />);
|
||||
|
||||
expect(container.querySelector('.custom-class')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-members')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('renders footer via renderFooter prop', () => {
|
||||
|
||||
@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('adds a row when "Add another" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('removes a row when trash button is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('respects minRows constraint when removing rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} minRows={2} />);
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('cannot remove rows below minRows=1 default', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('preserves data in other rows when removing one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('email validation', () => {
|
||||
it('shows email validation error when email is invalid and role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('shows inline error for invalid email field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears validation error when email is corrected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -104,7 +104,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('role validation', () => {
|
||||
it('shows role validation error when role is missing', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears role validation error when role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -159,7 +159,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('combined validation', () => {
|
||||
it('shows combined error when both email and role are invalid', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -186,7 +186,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('touched rows', () => {
|
||||
it('only validates touched rows (rows with email or role)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
|
||||
@@ -34,7 +34,7 @@ describe('InvalidQueryState', () => {
|
||||
});
|
||||
|
||||
it('runs the callback, then opens support', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onContactSupport = jest.fn();
|
||||
render(
|
||||
<InvalidQueryState
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import SearchBar from '../SearchBar';
|
||||
@@ -40,9 +40,7 @@ function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
|
||||
}
|
||||
|
||||
function searchContent(): HTMLElement {
|
||||
return screen
|
||||
.getByTestId('list-search')
|
||||
.querySelector('.cm-content') as HTMLElement;
|
||||
return within(screen.getByTestId('list-search')).getByRole('textbox');
|
||||
}
|
||||
|
||||
describe('SearchBar — run on blur', () => {
|
||||
|
||||
@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('selects a view by id', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-view-2`));
|
||||
@@ -61,7 +61,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('filters views by name and says when none match', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderRail();
|
||||
const search = screen.getByTestId(`${PREFIX}-view-search-field`);
|
||||
|
||||
@@ -109,7 +109,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('offers save, save as and reset for a modified custom view', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({
|
||||
activeViewId: 'view-1',
|
||||
@@ -138,7 +138,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('saves the current filters as a named view from the dialog', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({ onViewSaved });
|
||||
|
||||
@@ -164,7 +164,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('opens the save dialog empty again after a cancel', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail({ isModified: true });
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-save-as-new`));
|
||||
@@ -183,7 +183,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('renames a custom view from a dialog filled with its name', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewRenamed = jest.fn();
|
||||
const props = renderRail({ onViewRenamed });
|
||||
|
||||
@@ -206,7 +206,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('refills the rename dialog with the name of the view it opens for', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
|
||||
|
||||
@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log link from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -128,7 +128,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open when a ⋯ menu item is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -152,7 +152,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('calls handleOpenInExplorer when "Open in Explorer" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const handleOpenInExplorer = jest.fn();
|
||||
|
||||
renderDrawer({ handleOpenInExplorer });
|
||||
@@ -163,7 +163,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes from the close button and from Escape', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -176,7 +176,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes on a mousedown outside the drawer and not on one inside it', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -196,7 +196,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open on a mousedown in a data-log-detail-ignore region', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -258,7 +258,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates to the next / previous log with the Down / Up arrow keys', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1'), makeLog('log-2')];
|
||||
const onNavigateLog = jest.fn();
|
||||
const onScrollToLog = jest.fn();
|
||||
@@ -276,7 +276,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('does not navigate past the first log on ArrowUp', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
@@ -287,7 +287,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates via the header up / down buttons and disables them at boundaries', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
|
||||
@@ -1,46 +1,39 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import LogStateIndicator from './LogStateIndicator';
|
||||
|
||||
describe('LogStateIndicator', () => {
|
||||
it('renders correctly with default props', () => {
|
||||
const { container } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
render(<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />);
|
||||
const indicator = screen.getByTestId('log-state-indicator');
|
||||
expect(indicator).toHaveClass('log-state-indicator');
|
||||
expect(indicator).not.toHaveClass('isActive');
|
||||
expect(within(indicator).getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator.classList.contains('log-state-indicator')).toBe(true);
|
||||
expect(indicator.classList.contains('isActive')).toBe(false);
|
||||
expect(container.querySelector('.line')).toBeTruthy();
|
||||
expect(
|
||||
container.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('renders correctly with different types', () => {
|
||||
const { container: containerInfo } = render(
|
||||
const { rerender } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerInfo.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
|
||||
const { container: containerWarning } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="WARNING" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerWarning
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-warn-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-warn-0',
|
||||
);
|
||||
|
||||
const { container: containerError } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="ERROR" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerError
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-error-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-error-0',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,8 +138,11 @@ function LogStateIndicator({
|
||||
const severityClass = getSeverityClass(severityText, severityNumber);
|
||||
|
||||
return (
|
||||
<div className="log-state-indicator">
|
||||
<div className={cx('line', fontSize, severityClass)} />
|
||||
<div className="log-state-indicator" data-testid="log-state-indicator">
|
||||
<div
|
||||
className={cx('line', fontSize, severityClass)}
|
||||
data-testid="log-state-indicator-line"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,7 +128,9 @@ function OptionsMenu({
|
||||
>
|
||||
<span className="menu-row">
|
||||
{size}
|
||||
{fontSizeValue === size && <Check size={14} />}
|
||||
{fontSizeValue === size && (
|
||||
<Check size={14} data-testid="font-size-option-check" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
@@ -156,7 +158,7 @@ function OptionsMenu({
|
||||
</Button>
|
||||
</div>
|
||||
<div className="horizontal-line" />
|
||||
<div className="menu-container">
|
||||
<div className="menu-container" data-testid="format-options-menu">
|
||||
<div className="title">FORMAT</div>
|
||||
|
||||
<div className="menu-items">
|
||||
@@ -170,7 +172,9 @@ function OptionsMenu({
|
||||
<div className={cx('item-label')}>
|
||||
{item.label}
|
||||
|
||||
{selectedItem === item.key && <Check size={12} />}
|
||||
{selectedItem === item.key && (
|
||||
<Check size={12} data-testid="format-check-icon" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
|
||||
@@ -34,13 +35,14 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
mockUpdateFormatting.mockClear();
|
||||
});
|
||||
|
||||
function setup(): {
|
||||
async function setup(): Promise<{
|
||||
user: ReturnType<typeof userEvent.setup>;
|
||||
getByTestId: ReturnType<typeof render>['getByTestId'];
|
||||
findItemByLabel: (label: string) => Element | undefined;
|
||||
formatOnChange: jest.Mock<any, any>;
|
||||
maxLinesOnChange: jest.Mock<any, any>;
|
||||
fontSizeOnChange: jest.Mock<any, any>;
|
||||
} {
|
||||
}> {
|
||||
const user = userEvent.setup();
|
||||
const items = [
|
||||
{ key: 'raw', label: 'Raw', data: { title: 'max lines per row' } },
|
||||
{ key: 'list', label: 'Default' },
|
||||
@@ -76,16 +78,11 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Open the popover menu by default for each test
|
||||
const formatButton = getByTestId('periscope-btn-format-options');
|
||||
fireEvent.click(formatButton);
|
||||
|
||||
const getMenuItems = (): Element[] =>
|
||||
Array.from(document.querySelectorAll('.menu-items .item'));
|
||||
const findItemByLabel = (label: string): Element | undefined =>
|
||||
getMenuItems().find((el) => (el.textContent || '').includes(label));
|
||||
await user.click(formatButton);
|
||||
|
||||
return {
|
||||
user,
|
||||
getByTestId,
|
||||
findItemByLabel,
|
||||
formatOnChange,
|
||||
maxLinesOnChange,
|
||||
fontSizeOnChange,
|
||||
@@ -94,31 +91,36 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Covers: opens menu, changes format selection, updates max-lines, changes font size
|
||||
it('opens and toggles format selection', async () => {
|
||||
const { findItemByLabel, formatOnChange } = setup();
|
||||
const { user, formatOnChange } = await setup();
|
||||
|
||||
// Assert initial selection
|
||||
const columnItem = findItemByLabel('Column') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(columnItem.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-table')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Change selection to 'Raw'
|
||||
const rawItem = findItemByLabel('Raw') as Element;
|
||||
fireEvent.click(rawItem as HTMLElement);
|
||||
await user.click(screen.getByTestId('format-option-raw'));
|
||||
await waitFor(() => {
|
||||
const rawEl = findItemByLabel('Raw') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(rawEl.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-raw')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(formatOnChange).toHaveBeenCalledWith('raw');
|
||||
});
|
||||
|
||||
it('increments max-lines and calls onChange', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
|
||||
// Increment max lines
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const initial = Number(input.value);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
await user.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Number(input.value)).toBe(initial + 1);
|
||||
@@ -129,9 +131,8 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('clamps a typed max-lines value to 10', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '15');
|
||||
@@ -142,10 +143,9 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('stops max-lines at 10', async () => {
|
||||
const { getByTestId } = setup();
|
||||
const { user, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const increment = screen.getByRole('button', { name: 'More lines per row' });
|
||||
const user = userEvent.setup();
|
||||
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await user.click(increment);
|
||||
@@ -155,19 +155,23 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('changes font size to MEDIUM and calls onChange', async () => {
|
||||
const { fontSizeOnChange, getByTestId } = setup();
|
||||
const { user, fontSizeOnChange, getByTestId } = await setup();
|
||||
// Open font dropdown
|
||||
fireEvent.click(getByTestId('font-size-select'));
|
||||
await user.click(getByTestId('font-size-select'));
|
||||
|
||||
// Choose MEDIUM
|
||||
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
await user.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.MEDIUM}`)).getByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.SMALL}`)).queryByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() => {
|
||||
@@ -212,16 +216,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
renderWithOnOpen(undefined, 'table');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render "Edit columns" row when format is not table', () => {
|
||||
renderWithOnOpen(jest.fn(), 'raw');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
|
||||
@@ -233,7 +237,7 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
expect(onOpenColumns).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => {
|
||||
// Popover content unmounts on close.
|
||||
expect(document.querySelector('.menu-container')).toBeNull();
|
||||
expect(screen.queryByTestId('format-option-table')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,8 +74,7 @@ function Harness({
|
||||
}
|
||||
|
||||
const getView = (): EditorView => {
|
||||
const dom = document.querySelector('.cm-editor');
|
||||
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
|
||||
const view = EditorView.findFromDOM(screen.getByTestId('markdown-editor'));
|
||||
if (!view) {
|
||||
throw new Error('editor view not mounted');
|
||||
}
|
||||
@@ -151,11 +150,9 @@ describe('MarkdownEditor', () => {
|
||||
render(<Harness initialValue={'## Runbook\nowner {{team}}'} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.cm-md-heading')).toBeInTheDocument();
|
||||
expect(screen.getByText('## Runbook')).toHaveClass('cm-md-heading');
|
||||
});
|
||||
expect(document.querySelector('.cm-md-variable')).toHaveTextContent(
|
||||
'{{team}}',
|
||||
);
|
||||
expect(screen.getByText('{{team}}')).toHaveClass('cm-md-variable');
|
||||
});
|
||||
|
||||
describe('uncontrolled document', () => {
|
||||
|
||||
@@ -189,7 +189,13 @@ function MembersTable({
|
||||
<span className="members-pagination-range">
|
||||
{range[0]} — {range[1]}
|
||||
</span>
|
||||
<span className="members-pagination-total"> of {_total}</span>
|
||||
<span
|
||||
className="members-pagination-total"
|
||||
data-testid="members-pagination-total"
|
||||
>
|
||||
{' '}
|
||||
of {_total}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('MembersTable', () => {
|
||||
const onRowClick = jest.fn() as jest.MockedFunction<
|
||||
(member: MemberRow) => void
|
||||
>;
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<MembersTable
|
||||
@@ -88,7 +88,7 @@ describe('MembersTable', () => {
|
||||
|
||||
it('renders DELETED badge and calls onRowClick when a deleted member row is clicked', async () => {
|
||||
const onRowClick = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const deletedMember: MemberRow = {
|
||||
id: 'user-del',
|
||||
name: 'Dave Deleted',
|
||||
@@ -129,7 +129,7 @@ describe('MembersTable', () => {
|
||||
});
|
||||
|
||||
it('hides pagination when total does not exceed pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -139,12 +139,12 @@ describe('MembersTable', () => {
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
screen.queryByTestId('members-pagination-total'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows pagination when total exceeds pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -153,11 +153,8 @@ describe('MembersTable', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.members-pagination-total'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('members-pagination-total')).toHaveTextContent(
|
||||
'of 25',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import MessageTip from './index';
|
||||
|
||||
@@ -35,13 +35,13 @@ describe('MessageTip', () => {
|
||||
// taken from antd docs
|
||||
// https://github.com/ant-design/ant-design/blob/master/components/alert/__tests__/index.test.tsx
|
||||
it('custom action', () => {
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<MessageTip
|
||||
show
|
||||
message="Success Tips"
|
||||
action={<button type="button">Close</button>}
|
||||
/>,
|
||||
);
|
||||
expect(container.firstChild).toMatchSnapshot();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
|
||||
|
||||
exports[`MessageTip custom action 1`] = `
|
||||
.c0 {
|
||||
<DocumentFragment>
|
||||
.c0 {
|
||||
-webkit-align-items: center;
|
||||
-webkit-box-align: center;
|
||||
-ms-flex-align: center;
|
||||
@@ -9,46 +10,47 @@ exports[`MessageTip custom action 1`] = `
|
||||
}
|
||||
|
||||
<div
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-content"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
class="ant-alert-content"
|
||||
>
|
||||
Success Tips
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
>
|
||||
Success Tips
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
@@ -632,7 +632,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -746,6 +750,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onKeyDown={(e): void => {
|
||||
if ((e.key === 'Enter' || e.key === SPACEKEY) && isActive) {
|
||||
e.stopPropagation();
|
||||
@@ -777,7 +782,9 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{(option.type === 'custom' || option.type === 'regex') && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
{option.value && ensureValidOption(option.value) && (
|
||||
<Button
|
||||
@@ -1562,6 +1569,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-multiselect-dropdown"
|
||||
data-testid="custom-multiselect-dropdown"
|
||||
onMouseDown={handleDropdownMouseDown}
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
@@ -1583,6 +1591,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
active: activeIndex === 0,
|
||||
})}
|
||||
key={`all-option-${allOptionsSelected}`}
|
||||
data-testid="all-option"
|
||||
id="option-0"
|
||||
onMouseEnter={(): void => {
|
||||
setActiveIndex(0);
|
||||
@@ -1641,7 +1650,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divider" />
|
||||
<div className="divider" data-testid="all-option-divider" />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1711,7 +1720,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
)}
|
||||
|
||||
{/* Navigation help footer */}
|
||||
<div className="navigation-footer" role="note">
|
||||
<div
|
||||
className="navigation-footer"
|
||||
role="note"
|
||||
data-testid="navigation-footer"
|
||||
>
|
||||
{!loading &&
|
||||
!errorMessage &&
|
||||
!noDataMessage &&
|
||||
@@ -1726,7 +1739,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1734,7 +1747,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1744,7 +1757,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && !waitingMessage && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
@@ -1959,6 +1972,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
'ant-select-selection-item-active': isActive,
|
||||
'ant-select-selection-item-selected': isSelected,
|
||||
})}
|
||||
data-testid={`selected-tag-${value}`}
|
||||
style={
|
||||
isActive || isSelected
|
||||
? {
|
||||
|
||||
@@ -170,7 +170,11 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -220,6 +224,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
handleSelection();
|
||||
@@ -241,7 +246,9 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{option.type === 'custom' && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -268,6 +275,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
() => (
|
||||
<X
|
||||
size="md"
|
||||
data-testid="custom-select-clear"
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
if (onChange) {
|
||||
@@ -528,6 +536,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-select-dropdown"
|
||||
data-testid="custom-select-dropdown"
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
onScroll={handleDropdownScroll}
|
||||
@@ -587,7 +596,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -595,7 +604,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -605,7 +614,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
import type { CustomMultiSelectProps } from '../types';
|
||||
|
||||
// Mock scrollIntoView which isn't available in JSDOM
|
||||
window.HTMLElement.prototype.scrollIntoView = jest.fn();
|
||||
@@ -49,6 +50,26 @@ const mockGroupedOptions = [
|
||||
},
|
||||
];
|
||||
|
||||
function StatefulMultiSelect({
|
||||
initialValue,
|
||||
onChange,
|
||||
}: {
|
||||
initialValue: string[];
|
||||
onChange: CustomMultiSelectProps['onChange'];
|
||||
}): JSX.Element {
|
||||
const [value, setValue] = useState<string[] | string>(initialValue);
|
||||
return (
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
value={value}
|
||||
onChange={(next, option): void => {
|
||||
onChange?.(next, option);
|
||||
setValue(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
let user: ReturnType<typeof userEvent.setup>;
|
||||
let mockOnChange: jest.Mock;
|
||||
@@ -114,16 +135,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Verify the component renders without crashing
|
||||
expect(combobox).toBeInTheDocument();
|
||||
@@ -141,30 +154,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -188,49 +191,31 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should filter to show only Frontend and Backend with highlighted "end"
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "end" text in the options
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
|
||||
// Check that Frontend and Backend options are present with highlighted text
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Front') &&
|
||||
label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
const hasBackendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Back') && label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveTextContent(
|
||||
'Backend',
|
||||
);
|
||||
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
expect(hasBackendOption).toBe(true);
|
||||
|
||||
// Other options should be filtered out
|
||||
const hasDatabaseOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Database'),
|
||||
);
|
||||
const hasApiGatewayOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('API Gateway'),
|
||||
);
|
||||
|
||||
expect(hasDatabaseOption).toBe(false);
|
||||
expect(hasApiGatewayOption).toBe(false);
|
||||
expect(
|
||||
screen.queryByTestId('option-item-database'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('option-item-api-gateway'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,15 +231,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Type comma-separated values
|
||||
await user.type(searchInput, 'test1, test2, test3');
|
||||
}
|
||||
// Type comma-separated values
|
||||
await user.type(combobox, 'test1, test2, test3');
|
||||
|
||||
// Press Enter to create the comma-separated chips
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -294,14 +272,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-multiselect-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-label-text') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top (after ALL option if present)
|
||||
expect(optionTexts[0]).toBe('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toBe(screen.getByTestId('option-item-database'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -319,30 +296,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front' and highlight search term
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -362,21 +329,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -393,14 +352,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -411,13 +363,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -445,23 +395,19 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('option-item-frontend');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
// The active option should be an option in the dropdown
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option (goes back to ALL)
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('all-option');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
expect(activeOption?.textContent).toContain('ALL');
|
||||
expect(activeOption).toHaveTextContent('ALL');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -499,19 +445,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Tab again to move to next option
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -558,10 +499,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Delete the active chip
|
||||
@@ -575,11 +515,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify that the active chip (backend) is highlighted for deletion
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
expect(activeChip).toHaveTextContent('backend');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -688,9 +626,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByRole('checkbox'));
|
||||
|
||||
@@ -726,9 +662,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByText('Toggle'));
|
||||
|
||||
@@ -751,8 +685,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Database')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Gateway')).toBeInTheDocument();
|
||||
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
expect(screen.getByText('Refreshing values...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -770,8 +703,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -813,21 +745,17 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// All chips should be selected (have selected class)
|
||||
const selectedChips = document.querySelectorAll(
|
||||
'.ant-select-selection-item-selected',
|
||||
);
|
||||
const selectedChips = screen
|
||||
.getAllByTestId(/^selected-tag-/)
|
||||
.filter((chip) =>
|
||||
chip.classList.contains('ant-select-selection-item-selected'),
|
||||
);
|
||||
expect(selectedChips.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify that all expected chips are present AND selected
|
||||
const frontendChip = screen
|
||||
.getByText('frontend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const backendChip = screen
|
||||
.getByText('backend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const databaseChip = screen
|
||||
.getByText('database')
|
||||
.closest('.ant-select-selection-item');
|
||||
const frontendChip = screen.getByTestId('selected-tag-frontend');
|
||||
const backendChip = screen.getByTestId('selected-tag-backend');
|
||||
const databaseChip = screen.getByTestId('selected-tag-database');
|
||||
|
||||
expect(frontendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
expect(backendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
@@ -850,11 +778,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
if (clearButton) {
|
||||
await user.click(clearButton as Element);
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
}
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
});
|
||||
|
||||
it('CA-03: Individual chip removal', async () => {
|
||||
@@ -867,12 +792,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
// Find and click the close button on a chip
|
||||
const removeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
const removeButtons = screen.getAllByLabelText(/^Remove tag /);
|
||||
expect(removeButtons).toHaveLength(2);
|
||||
|
||||
await user.click(removeButtons[1] as Element);
|
||||
await user.click(removeButtons[1]);
|
||||
|
||||
// Should call onChange with one item removed
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -911,9 +834,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Dropdown should be hidden (not completely removed from DOM)
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(dropdown).toHaveStyle('pointer-events: none');
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -951,14 +875,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-input');
|
||||
}
|
||||
await user.type(combobox, 'custom-input');
|
||||
|
||||
// Press Enter in input field
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -984,18 +901,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'search-text');
|
||||
}
|
||||
await user.type(combobox, 'search-text');
|
||||
|
||||
// Verify search text is in input
|
||||
await waitFor(() => {
|
||||
expect(searchInput).toHaveValue('search-text');
|
||||
expect(combobox).toHaveValue('search-text');
|
||||
});
|
||||
|
||||
// Press Escape to close dropdown
|
||||
@@ -1003,9 +913,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close and search text should be cleared
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(searchInput).toHaveValue('');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(combobox).toHaveValue('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1029,8 +938,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(allOption).toBeInTheDocument();
|
||||
|
||||
// Check for divider after ALL option
|
||||
const divider = document.querySelector('.divider');
|
||||
expect(divider).toBeInTheDocument();
|
||||
expect(screen.getByTestId('all-option-divider')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1086,8 +994,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show navigation footer
|
||||
const footer = document.querySelector('.navigation-footer');
|
||||
expect(footer).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-footer')).toBeInTheDocument();
|
||||
|
||||
// Should show navigation hint
|
||||
expect(screen.getByText('to navigate')).toBeInTheDocument();
|
||||
@@ -1161,10 +1068,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
describe('Advanced Keyboard Navigation (AKN)', () => {
|
||||
it('AKN-01: Shift + Arrow + Del chip deletion', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
<StatefulMultiSelect
|
||||
initialValue={['frontend', 'backend', 'database']}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend', 'backend', 'database']}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -1176,12 +1082,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip - verify initial chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we're on the last chip (database)
|
||||
expect(activeChip?.textContent).toContain('database');
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Shift + Arrow to navigate to previous chip
|
||||
@@ -1189,12 +1093,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify we're on a different chip (backend)
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we moved to the previous chip (backend)
|
||||
expect(activeChip?.textContent).toContain('backend');
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Del to delete the active chip
|
||||
@@ -1203,8 +1105,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
// Verify the chip was deleted
|
||||
await waitFor(() => {
|
||||
// Check that the backend chip is no longer present
|
||||
const backendChip = document.querySelector('.ant-select-selection-item');
|
||||
expect(backendChip?.textContent).not.toContain('backend');
|
||||
expect(
|
||||
screen.queryByTestId('selected-tag-backend'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Verify onChange was called with the updated value (without backend)
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -1235,9 +1138,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close - check for hidden state
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
// The dropdown should be hidden with the hidden class
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1256,32 +1158,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const labelElement = item.querySelector('.option-label-text');
|
||||
return labelElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text should contain "front"
|
||||
@@ -1325,12 +1215,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should create custom value)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -1364,11 +1249,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith([], []);
|
||||
@@ -1426,19 +1308,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -1469,25 +1345,16 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1570,8 +1437,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Escape}');
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,9 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -29,9 +30,6 @@ const mockOptions = [
|
||||
{ label: 'Option 3', value: 'option3' },
|
||||
];
|
||||
|
||||
// CSS selector for retry button
|
||||
const RETRY_BUTTON_SELECTOR = '[data-testid="retry-button"]';
|
||||
|
||||
describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -61,8 +59,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Check that retry button (ReloadOutlined icon) is present
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
|
||||
@@ -88,11 +85,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
expect(screen.getByText(errorMessage)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call onRetry function when retry button is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const mockOnRetry = jest.fn();
|
||||
const errorMessage = 'Internal Server Error (500)';
|
||||
|
||||
@@ -108,7 +105,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Wait for dropdown to appear
|
||||
await waitFor(() => {
|
||||
@@ -116,10 +113,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Find and click the retry button
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryButton as Element);
|
||||
await user.click(screen.getByTestId('retry-button'));
|
||||
|
||||
// Verify onRetry was called
|
||||
expect(mockOnRetry).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -4,9 +4,10 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -156,6 +157,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('removes a tag when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleChange = jest.fn();
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
@@ -166,10 +168,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
);
|
||||
|
||||
// Find close button on Option 1 tag and click it
|
||||
const closeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
fireEvent.click(closeButtons[0]);
|
||||
await user.click(screen.getByLabelText('Remove tag option1'));
|
||||
|
||||
// Verify onChange was called with remaining option
|
||||
expect(handleChange).toHaveBeenCalledWith(
|
||||
@@ -179,39 +178,24 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('filters options when searching', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Type into search box - get input directly
|
||||
const inputElement = selectElement.querySelector('input');
|
||||
if (inputElement) {
|
||||
fireEvent.change(inputElement, { target: { value: '2' } });
|
||||
}
|
||||
// Type into search box - the combobox is the search input
|
||||
await user.type(selectElement, '2');
|
||||
|
||||
// Wait for the dropdown filtering to happen
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector(
|
||||
'.custom-multiselect-dropdown',
|
||||
);
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Verify Option 2 is visible in the dropdown
|
||||
const options = document.querySelectorAll('.option-label-text');
|
||||
let foundOption2 = false;
|
||||
|
||||
options.forEach((option) => {
|
||||
const text = option.textContent || '';
|
||||
if (text.includes('Option 2')) {
|
||||
foundOption2 = true;
|
||||
}
|
||||
});
|
||||
|
||||
expect(foundOption2).toBe(true);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('option-item-option1')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(
|
||||
within(screen.getByTestId('custom-multiselect-dropdown'))
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((option) => option.dataset.testid),
|
||||
).toStrictEqual(['option-item-2', 'option-item-option2']);
|
||||
});
|
||||
|
||||
it('renders grouped options correctly', async () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -67,34 +66,19 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Check that custom value appears in dropdown with custom tag
|
||||
await waitFor(() => {
|
||||
// Find the custom option with "fro" text and "Custom" badge
|
||||
const customOptions = screen.getAllByText('fro');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-fro');
|
||||
expect(customOption).toHaveTextContent('fro');
|
||||
|
||||
// Verify it has the custom badge
|
||||
const optionItem = customOption?.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
expect(badge).toBeInTheDocument();
|
||||
expect(badge?.textContent).toBe('Custom');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the custom value
|
||||
@@ -120,30 +104,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -174,14 +148,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-content') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top
|
||||
expect(optionTexts[0]).toContain('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toHaveTextContent('Database');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -197,30 +168,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front'
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -238,21 +199,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -267,14 +220,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -285,13 +231,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -313,19 +257,15 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
// Verify it's the first option (Frontend)
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Frontend');
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,8 +350,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Tab}');
|
||||
|
||||
// Should still be within dropdown context
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -453,8 +392,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -471,8 +409,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -605,8 +542,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Focus should remain manageable
|
||||
@@ -679,8 +615,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -714,8 +649,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -732,32 +666,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const contentElement = item.querySelector('.option-content');
|
||||
return contentElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text includes "Custom" badge, so check for "front" in the text
|
||||
@@ -807,12 +729,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should close dropdown)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -847,11 +764,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -870,11 +784,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should clear the single selection
|
||||
expect(mockOnChange).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -927,19 +838,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -962,12 +867,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
// Should be able to type even with loading state
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'test');
|
||||
}
|
||||
await user.type(combobox, 'test');
|
||||
|
||||
// Should not be blocked by loading spinner
|
||||
expect(combobox).not.toBeDisabled();
|
||||
@@ -986,25 +886,16 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1076,8 +967,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close after selection in single select
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -93,11 +99,12 @@ describe('CustomSelect Component', () => {
|
||||
// Dropdown should only show Option 2
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector('.custom-select-dropdown');
|
||||
const dropdownElement = screen.getByTestId('custom-select-dropdown');
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Use a simple approach to verify filtering
|
||||
const allOptionsInDropdown = document.querySelectorAll('.option-item');
|
||||
const allOptionsInDropdown =
|
||||
within(dropdownElement).queryAllByTestId(/^option-item-/);
|
||||
let foundOption2 = false;
|
||||
|
||||
allOptionsInDropdown.forEach((option) => {
|
||||
|
||||
@@ -40,7 +40,7 @@ function ListViewOrderBy({
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [selectOptions, setSelectOptions] = useState<
|
||||
{ label: string; value: string }[]
|
||||
{ label: string; value: string; 'data-testid': string }[]
|
||||
>([]);
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
@@ -75,8 +75,16 @@ function ListViewOrderBy({
|
||||
|
||||
setSelectOptions(
|
||||
uniqueKeys.flatMap((key) => [
|
||||
{ label: `${key} (desc)`, value: `${key}:desc` },
|
||||
{ label: `${key} (asc)`, value: `${key}:asc` },
|
||||
{
|
||||
label: `${key} (desc)`,
|
||||
value: `${key}:desc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
{
|
||||
label: `${key} (asc)`,
|
||||
value: `${key}:asc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
]),
|
||||
);
|
||||
}, [data, searchInput, extraKeysSignature]);
|
||||
|
||||
@@ -59,9 +59,9 @@ const openDropdown = (): void => {
|
||||
};
|
||||
|
||||
const getOptionLabels = (): string[] =>
|
||||
Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(
|
||||
(node) => node.textContent ?? '',
|
||||
);
|
||||
screen
|
||||
.queryAllByTestId('list-view-order-by-option')
|
||||
.map((node) => node.textContent ?? '');
|
||||
|
||||
describe('ListViewOrderBy', () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import OverflowInputToolTip from './OverflowInputToolTip';
|
||||
|
||||
const TOOLTIP_INNER_SELECTOR = '.ant-tooltip-inner';
|
||||
// Utility to mock overflow behaviour on inputs / elements.
|
||||
// Stubs HTMLElement.prototype.clientWidth, scrollWidth and offsetWidth used by component.
|
||||
function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
@@ -22,21 +21,17 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
function queryTooltipInner(): HTMLElement | null {
|
||||
// find element that has role="tooltip" (could be the inner itself)
|
||||
const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');
|
||||
if (!tooltip) {
|
||||
return document.querySelector(TOOLTIP_INNER_SELECTOR);
|
||||
}
|
||||
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
|
||||
|
||||
// if the role element is already the inner, return it; otherwise return its descendant
|
||||
if (tooltip.classList.contains('ant-tooltip-inner')) {
|
||||
return tooltip;
|
||||
}
|
||||
return (
|
||||
(tooltip.querySelector(TOOLTIP_INNER_SELECTOR) as HTMLElement) ??
|
||||
document.querySelector(TOOLTIP_INNER_SELECTOR)
|
||||
);
|
||||
async function hoverPastOpenDelay(element: HTMLElement): Promise<void> {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
await user.hover(element);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(ANTD_TOOLTIP_OPEN_DELAY_MS * 2);
|
||||
});
|
||||
}
|
||||
|
||||
describe('OverflowInputToolTip', () => {
|
||||
@@ -44,6 +39,10 @@ describe('OverflowInputToolTip', () => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('shows tooltip when content overflows and input is clamped at maxAutoWidth', async () => {
|
||||
mockOverflow(150, 250); // clientWidth >= maxAutoWidth (150), scrollWidth > clientWidth
|
||||
|
||||
@@ -51,16 +50,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).not.toBeNull();
|
||||
});
|
||||
|
||||
const tooltipInner = queryTooltipInner();
|
||||
if (!tooltipInner) {
|
||||
throw new Error('Tooltip inner not found');
|
||||
}
|
||||
const tooltip = await screen.findByRole('tooltip');
|
||||
expect(
|
||||
within(tooltipInner).getByText('Very long overflowing text'),
|
||||
within(tooltip).getByText('Very long overflowing text'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -69,11 +61,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Short text" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
|
||||
@@ -81,11 +71,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Long but input not clamped" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uncontrolled input allows typing', async () => {
|
||||
@@ -102,24 +90,20 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Overflowing!" disabled />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
|
||||
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = container.querySelector('.overflow-input-mirror');
|
||||
const input = container.querySelector('input') as HTMLInputElement | null;
|
||||
render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = screen.getByTestId('overflow-input-mirror');
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
expect(mirror).toBeTruthy();
|
||||
expect(mirror?.textContent).toBe('Snapshot');
|
||||
expect(input).toBeTruthy();
|
||||
expect(input?.value).toBe('Snapshot');
|
||||
expect(mirror.textContent).toBe('Snapshot');
|
||||
expect(input).toHaveValue('Snapshot');
|
||||
|
||||
// width should be set inline (component calculates width on mount)
|
||||
expect(input?.getAttribute('style')).toContain('width:');
|
||||
expect(input.getAttribute('style')).toContain('width:');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,7 +49,12 @@ function OverflowInputToolTip({
|
||||
|
||||
return (
|
||||
<>
|
||||
<span ref={mirrorRef} aria-hidden className="overflow-input-mirror" />
|
||||
<span
|
||||
ref={mirrorRef}
|
||||
aria-hidden
|
||||
className="overflow-input-mirror"
|
||||
data-testid="overflow-input-mirror"
|
||||
/>
|
||||
<Tooltip title={tooltipTitle} placement={tooltipPlacement}>
|
||||
<Input
|
||||
{...rest}
|
||||
|
||||
@@ -317,23 +317,20 @@ function QuerySearch({
|
||||
500,
|
||||
);
|
||||
|
||||
const toggleSuggestions = useCallback(
|
||||
(timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (isFocused) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
const toggleSuggestions = useCallback((timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (editorRef.current.hasFocus) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
},
|
||||
[isFocused],
|
||||
);
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
}, []);
|
||||
|
||||
const fetchKeySuggestions = useCallback(
|
||||
async (searchText?: string): Promise<void> => {
|
||||
@@ -1597,7 +1594,10 @@ function QuerySearch({
|
||||
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
|
||||
{isScopedFilter && !showScopeChip ? (
|
||||
<Tooltip title={initialExpression || ''} placement="left">
|
||||
<div className="query-search-initial-scope-label">
|
||||
<div
|
||||
className="query-search-initial-scope-label"
|
||||
data-testid="query-search-initial-scope-label"
|
||||
>
|
||||
<Filter
|
||||
size={14}
|
||||
style={{
|
||||
|
||||
@@ -168,6 +168,7 @@ export function renderRecentDeleteButton(
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'cm-recent-delete';
|
||||
btn.dataset.testid = 'query-search-recent-delete';
|
||||
btn.setAttribute('aria-label', 'Remove from recent searches');
|
||||
btn.title = 'Remove from recent searches';
|
||||
btn.textContent = '×';
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
@@ -19,6 +19,7 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
|
||||
const EDITOR_TEST_ID = 'query-aggregation-editor';
|
||||
// CodeMirror's suggestion popup is slow to open under a parallel jest run.
|
||||
@@ -116,7 +117,7 @@ async function enterAggregation(
|
||||
queryData: IBuilderQuery = aiQuery,
|
||||
currentQuery?: Query,
|
||||
): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryAggregationSelect queryData={queryData} />
|
||||
@@ -125,12 +126,9 @@ async function enterAggregation(
|
||||
{ queryBuilderOverrides: currentQuery && { currentQuery } },
|
||||
);
|
||||
|
||||
const content = (
|
||||
await screen.findByTestId(EDITOR_TEST_ID)
|
||||
).querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('CodeMirror content element not rendered');
|
||||
}
|
||||
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
|
||||
'textbox',
|
||||
);
|
||||
await user.click(content);
|
||||
// Typed keys drop under load: a re-render's dispatch discards DOM input CodeMirror hasn't read yet.
|
||||
await user.paste(text);
|
||||
@@ -138,10 +136,10 @@ async function enterAggregation(
|
||||
}
|
||||
|
||||
function suggestionLabels(): string[] {
|
||||
return Array.from(
|
||||
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
|
||||
(label) => label.textContent ?? '',
|
||||
).sort();
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((option) => option.textContent ?? '')
|
||||
.sort();
|
||||
}
|
||||
|
||||
describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
@@ -161,9 +159,10 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
async ({ aggregation, fieldDataType, labels }) => {
|
||||
await enterAggregation(aggregation);
|
||||
|
||||
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual(labels);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
expect(
|
||||
aiKeysRequests.map((params) => ({
|
||||
@@ -185,14 +184,13 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]),
|
||||
{ timeout: SUGGESTIONS_TIMEOUT_MS },
|
||||
);
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
beforeAll(() => {
|
||||
mockCodeMirrorDomApis();
|
||||
@@ -110,11 +111,7 @@ async function renderAndType(text: string): Promise<HTMLElement> {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, text);
|
||||
return editor;
|
||||
@@ -128,32 +125,26 @@ async function typeKeyThenEnterOperatorContext(
|
||||
): Promise<void> {
|
||||
const editor = await renderAndType(key);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain(expectedKeyLabel);
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
|
||||
|
||||
// skipClick: a click would reset the caret to position 0 under the mocked
|
||||
// DOM rects; we need the space appended at the end of the typed key.
|
||||
await userEvent.type(editor, ' ', { skipClick: true });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('=');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, '=');
|
||||
}
|
||||
|
||||
function visibleOptionLabels(): string[] {
|
||||
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(
|
||||
(el) => el.textContent ?? '',
|
||||
);
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((el) => el.textContent ?? '');
|
||||
}
|
||||
|
||||
describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows one deduped suggestion per key name in normal mode', async () => {
|
||||
await renderAndType('statu');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'status.code');
|
||||
|
||||
const statusOptions = visibleOptionLabels().filter(
|
||||
(label) => label === 'status.code',
|
||||
@@ -164,9 +155,7 @@ describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows context-scoped suggestions for a complete context prefix', async () => {
|
||||
await renderAndType('attribute.');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('attribute.status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
|
||||
|
||||
const labels = visibleOptionLabels();
|
||||
// Literal key name match ranks first
|
||||
|
||||
@@ -2,7 +2,9 @@ import { EditorView } from '@uiw/react-codemirror';
|
||||
import { getFieldKeySuggestions } from 'api/querySuggestions/getFieldKeySuggestions';
|
||||
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
@@ -14,8 +16,9 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
// Mock DOM APIs that CodeMirror needs
|
||||
beforeAll(() => {
|
||||
@@ -75,8 +78,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// CodeMirror renders a contenteditable div, so we check for the container
|
||||
const editorContainer = document.querySelector('.query-where-clause-editor');
|
||||
expect(editorContainer).toBeInTheDocument();
|
||||
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches key suggestions when typing a key (debounced)', async () => {
|
||||
@@ -94,14 +96,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find the CodeMirror editor contenteditable element
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
|
||||
// Focus and type into the editor
|
||||
await userEvent.click(editor);
|
||||
@@ -141,12 +137,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
|
||||
|
||||
@@ -162,6 +153,49 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
await expect(screen.findByText('200')).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the value suggestions open when the key suggestions load', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { held, release } = holdResponse();
|
||||
const mockedGetKeys = jest.mocked(getFieldKeySuggestions);
|
||||
mockedGetKeys.mockClear();
|
||||
mockedGetKeys.mockImplementationOnce(async () => {
|
||||
await held;
|
||||
return { status: 'success', data: { complete: true, keys: {} } };
|
||||
});
|
||||
jest.mocked(getFieldValueSuggestions).mockResolvedValueOnce({
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
values: {
|
||||
stringValues: ['payment-service'],
|
||||
numberValues: [],
|
||||
boolValues: [],
|
||||
relatedValues: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn()}
|
||||
queryData={initialQueriesMap.logs.builder.queryData[0]}
|
||||
dataSource={DataSource.LOGS}
|
||||
/>,
|
||||
);
|
||||
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await user.click(editor);
|
||||
await user.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
|
||||
await screen.findByText('payment-service');
|
||||
await waitFor(() => expect(mockedGetKeys).toHaveBeenCalled());
|
||||
|
||||
release();
|
||||
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
|
||||
expect(screen.getByText('payment-service')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches key suggestions on mount for LOGS', async () => {
|
||||
// Use real timers for CodeMirror integration tests
|
||||
const mockedGetKeysOnMount = getFieldKeySuggestions as jest.MockedFunction<
|
||||
@@ -203,12 +237,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
|
||||
|
||||
@@ -255,11 +284,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -268,7 +294,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
|
||||
it('shows the locked scope as a chip in place of the scope icon', () => {
|
||||
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -283,12 +309,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
expect(chip).toHaveTextContent('+1');
|
||||
expect(chip).not.toHaveTextContent('kind_string');
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.queryByTestId('query-search-initial-scope-label'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the scope icon unless the chip is asked for', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -301,7 +327,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
screen.queryByTestId('query-search-scope-chip'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.getByTestId('query-search-initial-scope-label'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -341,11 +367,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -371,13 +394,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize and the expression to be set
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
// CodeMirror stores content in .cm-content, check the text content
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
// CodeMirror may render the text in multiple ways, check if it contains our expression
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toContain('http.status_code');
|
||||
@@ -412,12 +431,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize with the initial expression
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toBe(initialExpression);
|
||||
},
|
||||
@@ -477,11 +493,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent.textContent || '').toBe(initialExpression);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
|
||||
@@ -6,18 +6,22 @@ import {
|
||||
import { EditorView } from '@uiw/react-codemirror';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
|
||||
import { fireEvent, render, userEvent, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { RECENTS_DISPLAY_CAP, RECENTS_SECTION } from '../QuerySearch/constants';
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_ROOT_SELECTOR = '.cm-editor';
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const TOOLTIP_SELECTOR = '.cm-tooltip-autocomplete';
|
||||
const COMPLETION_LABEL_SELECTOR = '.cm-completionLabel';
|
||||
const DELETE_BUTTON_SELECTOR = '.cm-recent-delete';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
const FRONTEND_FILTER = "service.name = 'frontend'";
|
||||
const STATUS_CODE_FILTER = "http.status_code = '500'";
|
||||
@@ -68,7 +72,7 @@ function saveLogsRecent(expression: string): void {
|
||||
}
|
||||
|
||||
function getEditorView(): EditorView | null {
|
||||
const root = document.querySelector<HTMLElement>(CM_ROOT_SELECTOR);
|
||||
const root = screen.queryByTestId(EDITOR_TEST_ID);
|
||||
return root ? EditorView.findFromDOM(root) : null;
|
||||
}
|
||||
|
||||
@@ -98,14 +102,7 @@ async function renderAndFocus(
|
||||
): Promise<HTMLElement> {
|
||||
renderLogsSearch(onChange);
|
||||
|
||||
const editor = await waitFor(
|
||||
() => {
|
||||
const element = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(element).toBeInTheDocument();
|
||||
return element as HTMLElement;
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
|
||||
await userEvent.click(editor);
|
||||
return editor;
|
||||
@@ -235,9 +232,7 @@ describe('QuerySearch recent searches', () => {
|
||||
await openRecents();
|
||||
|
||||
const option = await waitForPopupElement(() =>
|
||||
Array.from(
|
||||
document.querySelectorAll<HTMLElement>(COMPLETION_LABEL_SELECTOR),
|
||||
).find((element) => element.textContent === FRONTEND_FILTER),
|
||||
screen.queryByText(FRONTEND_FILTER),
|
||||
);
|
||||
// fireEvent: userEvent's pointerdown blurs the editor, closing the popup before CM's mousedown apply.
|
||||
fireEvent.mouseDown(option);
|
||||
@@ -253,7 +248,9 @@ describe('QuerySearch recent searches', () => {
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(document.querySelector(TOOLTIP_SELECTOR)).not.toBeInTheDocument();
|
||||
expect(
|
||||
within(screen.getByTestId(EDITOR_TEST_ID)).queryByLabelText('Completions'),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
@@ -266,7 +263,7 @@ describe('QuerySearch recent searches', () => {
|
||||
await openRecents();
|
||||
|
||||
const deleteButton = await waitForPopupElement(() =>
|
||||
document.querySelector<HTMLElement>(DELETE_BUTTON_SELECTOR),
|
||||
screen.queryByTestId('query-search-recent-delete'),
|
||||
);
|
||||
|
||||
// fireEvent: the button preventDefaults pointerdown, which makes userEvent.click drop the mouse chain.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { screen, within, type waitForOptions } from 'tests/test-utils';
|
||||
|
||||
export function findCompletionOption(
|
||||
editorTestId: string,
|
||||
label: string,
|
||||
options?: waitForOptions,
|
||||
): Promise<HTMLElement> {
|
||||
return within(screen.getByTestId(editorTestId)).findByText(
|
||||
(_, element) =>
|
||||
element?.getAttribute('role') === 'option' && element.textContent === label,
|
||||
undefined,
|
||||
options,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { screen, within } from 'tests/test-utils';
|
||||
|
||||
export async function findQueryEditorTextbox(): Promise<HTMLElement> {
|
||||
return within(
|
||||
await screen.findByTestId('query-where-clause-editor'),
|
||||
).getByRole('textbox');
|
||||
}
|
||||
@@ -361,7 +361,7 @@ describe('QueryAddOns', () => {
|
||||
});
|
||||
|
||||
it('calls handleSetQueryData when reduce-to value changes', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const query = baseQuery({
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
aggregations: [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { jest } from '@jest/globals';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import {
|
||||
Having,
|
||||
IBuilderQuery,
|
||||
@@ -146,7 +146,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
});
|
||||
|
||||
it('savePreviousQuery=true: metrics → meter saves previous query in session storage with appropriate key and query', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
@@ -155,9 +155,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
savePreviousQuery
|
||||
/>,
|
||||
);
|
||||
const trigger = document.querySelector(
|
||||
'.metrics-container .source-selector .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const trigger = within(
|
||||
screen.getByTestId('metrics-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
|
||||
await user.click(trigger);
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
});
|
||||
|
||||
it('savePreviousQuery=false: metrics → meter does not write to sessionStorage and applies defaults', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
// render WITHOUT savePreviousQuery enabled
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -193,9 +193,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
);
|
||||
|
||||
// open Source and choose Meter
|
||||
const trigger = document.querySelector(
|
||||
'.metrics-container .source-selector .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const trigger = within(
|
||||
screen.getByTestId('metrics-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(trigger);
|
||||
const meterOption = await screen.findByText('Meter');
|
||||
await user.click(meterOption);
|
||||
@@ -302,7 +302,7 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
});
|
||||
|
||||
it('updates query dataSource to TRACES saves previous query in session storage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -313,19 +313,12 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const logsTrigger = document.querySelector(
|
||||
'.query-data-source .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const logsTrigger = within(
|
||||
screen.getByTestId('query-data-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(logsTrigger);
|
||||
|
||||
const tracesContent = screen.getByText('Traces', {
|
||||
selector: '.ant-select-item-option-content',
|
||||
});
|
||||
|
||||
// click the option (prefer the option element; fallback to content)
|
||||
await user.click(
|
||||
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
|
||||
);
|
||||
await user.click(screen.getByTitle('Traces'));
|
||||
|
||||
// verify previousQuery store saved the current LOGS snapshot before switch
|
||||
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
|
||||
@@ -337,7 +330,7 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
);
|
||||
});
|
||||
it('updates query dataSource to TRACES does not saves previous query in session storage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -347,19 +340,12 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const logsTrigger = document.querySelector(
|
||||
'.query-data-source .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const logsTrigger = within(
|
||||
screen.getByTestId('query-data-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(logsTrigger);
|
||||
|
||||
const tracesContent = screen.getByText('Traces', {
|
||||
selector: '.ant-select-item-option-content',
|
||||
});
|
||||
|
||||
// click the option (prefer the option element; fallback to content)
|
||||
await user.click(
|
||||
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
|
||||
);
|
||||
await user.click(screen.getByTitle('Traces'));
|
||||
|
||||
// Assert that no snapshot was written
|
||||
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
|
||||
|
||||
@@ -197,7 +197,7 @@ export default function CheckboxFilterV2(
|
||||
onClear={onClear}
|
||||
/>
|
||||
{isOpen && isLoading && !hasLoadedOnce.current && (
|
||||
<section>
|
||||
<section data-testid="checkbox-filter-skeleton">
|
||||
<Skeleton paragraph={{ rows: 4 }} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -69,6 +69,7 @@ export function CheckboxFilterV2ValueRow({
|
||||
|
||||
<div
|
||||
role="button"
|
||||
data-testid={`checkbox-value-button-${value}`}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
className={cx(styles.valueButton, disabled && styles.isDisabled)}
|
||||
onClick={(): void => {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { server, rest } from 'mocks-server/server';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import { QuickFiltersSource } from '../../../../types';
|
||||
|
||||
@@ -31,11 +29,9 @@ describe('CheckboxFilterV2 - states', () => {
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('checkbox-filter-v2')).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('checkbox-filter-skeleton'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows skeleton when initially closed filter is opened for the first time', async () => {
|
||||
@@ -54,7 +50,7 @@ describe('CheckboxFilterV2 - states', () => {
|
||||
|
||||
// Filter starts closed - no skeleton, no content
|
||||
expect(
|
||||
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
|
||||
screen.queryByTestId('checkbox-filter-skeleton'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('checkbox-filter-empty'),
|
||||
@@ -65,11 +61,9 @@ describe('CheckboxFilterV2 - states', () => {
|
||||
await user.click(header);
|
||||
|
||||
// Should show skeleton while loading, NOT "No values found"
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('checkbox-filter-skeleton'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('checkbox-filter-empty'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { BadgeConfig } from '../itemRules';
|
||||
import { CheckedState } from '../../../../types';
|
||||
import { CheckboxFilterV2ValueRow } from '../CheckboxFilterV2ValueRow';
|
||||
|
||||
type OnOnlyOrAllClick = ComponentProps<
|
||||
typeof CheckboxFilterV2ValueRow
|
||||
>['onOnlyOrAllClick'];
|
||||
|
||||
describe('CheckboxFilterV2ValueRow', () => {
|
||||
const defaultProps = {
|
||||
value: 'production',
|
||||
@@ -111,7 +115,7 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
|
||||
it('does not call onOnlyOrAllClick when disabled + clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOnlyOrAllClick = jest.fn();
|
||||
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
|
||||
render(
|
||||
<CheckboxFilterV2ValueRow
|
||||
{...defaultProps}
|
||||
@@ -127,7 +131,7 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
|
||||
it('does not call onOnlyOrAllClick on keydown when disabled', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOnlyOrAllClick = jest.fn();
|
||||
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
|
||||
render(
|
||||
<CheckboxFilterV2ValueRow
|
||||
{...defaultProps}
|
||||
@@ -181,7 +185,7 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
|
||||
it('calls onOnlyOrAllClick on value text click', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOnlyOrAllClick = jest.fn();
|
||||
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
|
||||
render(
|
||||
<CheckboxFilterV2ValueRow
|
||||
{...defaultProps}
|
||||
@@ -196,7 +200,7 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
|
||||
it('calls onOnlyOrAllClick on Enter key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOnlyOrAllClick = jest.fn();
|
||||
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
|
||||
render(
|
||||
<CheckboxFilterV2ValueRow
|
||||
{...defaultProps}
|
||||
@@ -204,21 +208,17 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const valueButton = screen
|
||||
.getByText('production')
|
||||
.closest('[role="button"]');
|
||||
await user.tab();
|
||||
await user.tab();
|
||||
if (valueButton && document.activeElement === valueButton) {
|
||||
await user.keyboard('{Enter}');
|
||||
}
|
||||
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
|
||||
await user.keyboard('{Enter}');
|
||||
|
||||
expect(onOnlyOrAllClick).toHaveBeenCalled();
|
||||
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onOnlyOrAllClick on Space key', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOnlyOrAllClick = jest.fn();
|
||||
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
|
||||
render(
|
||||
<CheckboxFilterV2ValueRow
|
||||
{...defaultProps}
|
||||
@@ -226,16 +226,12 @@ describe('CheckboxFilterV2ValueRow', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const valueButton = screen
|
||||
.getByText('production')
|
||||
.closest('[role="button"]');
|
||||
await user.tab();
|
||||
await user.tab();
|
||||
if (valueButton && document.activeElement === valueButton) {
|
||||
await user.keyboard(' ');
|
||||
}
|
||||
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
|
||||
await user.keyboard(' ');
|
||||
|
||||
expect(onOnlyOrAllClick).toHaveBeenCalled();
|
||||
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows Toggle button', () => {
|
||||
|
||||
@@ -377,7 +377,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
);
|
||||
|
||||
const filtersSkeleton = (
|
||||
<div className="quick-filters-skeleton">
|
||||
<div className="quick-filters-skeleton" data-testid="quick-filters-skeleton">
|
||||
{Array.from({ length: 5 }).map((_, index) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<Skeleton.Input active size="small" key={index} />
|
||||
|
||||
@@ -195,12 +195,9 @@ describe('QuickFilters - AuthZ', () => {
|
||||
|
||||
renderWithSavedList();
|
||||
|
||||
await waitFor(() =>
|
||||
// eslint-disable-next-line testing-library/no-node-access
|
||||
expect(
|
||||
document.querySelector('.quick-filters-skeleton'),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
await expect(
|
||||
screen.findByTestId('quick-filters-skeleton'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByText(NOT_AUTHORIZED_TEXT)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(FILTER_SERVICE_NAME)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { lazy } from 'react';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import RouteTab from './index';
|
||||
import { RouteTabProps } from './types';
|
||||
@@ -69,21 +69,19 @@ describe('RouteTab component', () => {
|
||||
});
|
||||
|
||||
it('applies the layout class alongside a custom className', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<RouteTab routes={testRoutes} activeKey="Tab1" className="custom-tabs" />,
|
||||
);
|
||||
expect(container.querySelector('.ant-tabs')).toHaveClass(
|
||||
expect(screen.getByTestId('route-tab')).toHaveClass(
|
||||
'routeTab',
|
||||
'custom-tabs',
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the active tab content inside an overlay scrollbar', () => {
|
||||
const { container } = render(
|
||||
<RouteTab routes={testRoutes} activeKey="Tab1" />,
|
||||
);
|
||||
render(<RouteTab routes={testRoutes} activeKey="Tab1" />);
|
||||
expect(
|
||||
container.querySelector('.ant-tabs-tabpane-active > .overlay-scrollbar'),
|
||||
within(screen.getByRole('tabpanel')).getByTestId('overlay-scrollbar'),
|
||||
).toHaveTextContent('Dummy Component 1');
|
||||
});
|
||||
|
||||
|
||||
@@ -79,6 +79,7 @@ function RouteTab({
|
||||
return (
|
||||
<Tabs
|
||||
className={cx(styles.routeTab, className)}
|
||||
data-testid="route-tab"
|
||||
onChange={onChange}
|
||||
destroyInactiveTabPane
|
||||
activeKey={currentRoute?.key || activeKey}
|
||||
|
||||
@@ -192,7 +192,7 @@ function KeysTab({
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="keys-tab__loading">
|
||||
<div className="keys-tab__loading" data-testid="keys-tab-loading">
|
||||
<Skeleton active paragraph={{ rows: 4 }} />
|
||||
</div>
|
||||
);
|
||||
@@ -257,6 +257,7 @@ function KeysTab({
|
||||
role: string;
|
||||
tabIndex: number;
|
||||
'aria-label': string;
|
||||
'data-testid': string;
|
||||
} => ({
|
||||
onClick: async (): Promise<void> => {
|
||||
if (!isDisabled) {
|
||||
@@ -274,6 +275,7 @@ function KeysTab({
|
||||
role: 'button',
|
||||
tabIndex: 0,
|
||||
'aria-label': `Edit key ${record.name || 'options'}`,
|
||||
'data-testid': `keys-tab-row-${record.id}`,
|
||||
})}
|
||||
/>
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('"Create Key" is disabled when name is empty; enabled after typing a name', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
// The form only renders once the checks resolve, so waiting for it also
|
||||
@@ -92,7 +92,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('successful creation transitions to phase 2 with key displayed and security callout', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('add-key-name-input-field');
|
||||
@@ -109,7 +109,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('pressing Enter again while creating sends one request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requests = 0;
|
||||
server.use(
|
||||
rest.post(SA_KEYS_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -137,7 +137,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('copy button writes key to clipboard and shows toast.success', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderModal();
|
||||
|
||||
@@ -173,7 +173,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('keeps the footer usable when key create is denied', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderModal();
|
||||
@@ -208,7 +208,7 @@ describe('AddKeyModal', () => {
|
||||
});
|
||||
|
||||
it('Cancel button closes the modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const cancelBtn = await screen.findByTestId('add-key-cancel-btn');
|
||||
|
||||
@@ -106,7 +106,7 @@ describe('EditKeyModal (URL-controlled)', () => {
|
||||
});
|
||||
|
||||
it('save calls update API, shows toast, and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByPlaceholderText(/Enter key name/i);
|
||||
@@ -125,7 +125,7 @@ describe('EditKeyModal (URL-controlled)', () => {
|
||||
});
|
||||
|
||||
it('pressing Enter again while saving sends one request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requests = 0;
|
||||
server.use(
|
||||
rest.put(SA_KEY_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -175,7 +175,7 @@ describe('EditKeyModal (URL-controlled)', () => {
|
||||
});
|
||||
|
||||
it('cancel clears edit-key param and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = jest.fn();
|
||||
renderModal(mockKey, undefined, onUrlUpdate);
|
||||
|
||||
@@ -202,7 +202,7 @@ describe('EditKeyModal (URL-controlled)', () => {
|
||||
});
|
||||
|
||||
it('revoke flow: clicking Revoke Key shows confirmation inside same dialog', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
await screen.findByDisplayValue('Original Key Name');
|
||||
@@ -216,7 +216,7 @@ describe('EditKeyModal (URL-controlled)', () => {
|
||||
});
|
||||
|
||||
it('revoke flow: confirming revoke shows toast and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
await screen.findByDisplayValue('Original Key Name');
|
||||
|
||||
@@ -80,13 +80,13 @@ describe('KeysTab', () => {
|
||||
it('renders loading state', async () => {
|
||||
renderKeysTab({ isLoading: true });
|
||||
// Wait for authz to complete, then check for skeleton
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.ant-skeleton')).toBeInTheDocument();
|
||||
});
|
||||
await expect(
|
||||
screen.findByTestId('keys-tab-loading'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders empty state when no keys and clicking add sets add-key param', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = jest.fn();
|
||||
render(
|
||||
<NuqsTestingAdapter
|
||||
@@ -121,7 +121,7 @@ describe('KeysTab', () => {
|
||||
});
|
||||
|
||||
it('clicking a row sets the edit-key URL param', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -130,12 +130,7 @@ describe('KeysTab', () => {
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
const row = (await screen.findByText('Production Key')).closest('tr');
|
||||
if (!row) {
|
||||
throw new Error('Row not found');
|
||||
}
|
||||
|
||||
await user.click(row);
|
||||
await user.click(await screen.findByTestId('keys-tab-row-key-1'));
|
||||
|
||||
expect(onUrlUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -145,7 +140,7 @@ describe('KeysTab', () => {
|
||||
});
|
||||
|
||||
it('clicking revoke icon sets revoke-key URL param', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -167,7 +162,7 @@ describe('KeysTab', () => {
|
||||
});
|
||||
|
||||
it('handles successful key revocation via RevokeKeyModal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderKeysTab();
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('ServiceAccountsTable', () => {
|
||||
const onRowClick = jest.fn() as jest.MockedFunction<
|
||||
(row: ServiceAccountRow) => void
|
||||
>;
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<ServiceAccountsTable
|
||||
|
||||
@@ -61,7 +61,7 @@ export function ShiftOverlay({
|
||||
}
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
<div className="shift-overlay">
|
||||
<div className="shift-overlay" data-testid="shift-overlay">
|
||||
<div className="shift-overlay__panel">
|
||||
{navigationActions.map((action) => (
|
||||
<Shortcut
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
@@ -42,15 +42,15 @@ const baseActions: CmdAction[] = [
|
||||
|
||||
describe('ShiftOverlay', () => {
|
||||
it('renders nothing when not visible', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<ShiftOverlay visible={false} actions={baseActions} userRole="ADMIN" />,
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(screen.queryByTestId('shift-overlay')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing when no navigation shortcuts exist', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<ShiftOverlay
|
||||
visible
|
||||
actions={[
|
||||
@@ -65,13 +65,13 @@ describe('ShiftOverlay', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(screen.queryByTestId('shift-overlay')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders navigation shortcuts in a portal', () => {
|
||||
render(<ShiftOverlay visible actions={baseActions} userRole="ADMIN" />);
|
||||
|
||||
expect(document.body.querySelector('.shift-overlay')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('shift-overlay')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('Traces')).toBeInTheDocument();
|
||||
expect(screen.getByText('Metrics')).toBeInTheDocument();
|
||||
|
||||
@@ -4,18 +4,20 @@ import { Badge, type BadgeProps } from '@signozhq/ui/badge';
|
||||
interface TagBadgeProps {
|
||||
children: ReactNode;
|
||||
maxWidth?: BadgeProps['maxWidth'];
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
// The single sienna tag chip used wherever dashboards display tags — list rows
|
||||
// and the details header. Kept as one component so the tag
|
||||
// styling stays identical across all of them.
|
||||
function TagBadge({ children, maxWidth }: TagBadgeProps): JSX.Element {
|
||||
function TagBadge({ children, maxWidth, testId }: TagBadgeProps): JSX.Element {
|
||||
return (
|
||||
<Badge
|
||||
textTransform="none"
|
||||
color="archive"
|
||||
variant="outlined"
|
||||
maxWidth={maxWidth}
|
||||
testId={testId}
|
||||
>
|
||||
{children}
|
||||
</Badge>
|
||||
|
||||
@@ -67,6 +67,7 @@ function ColumnSelector<TData>({
|
||||
<Checkbox
|
||||
color="primary"
|
||||
id={`col-${col.id}`}
|
||||
testId={`${testId}-column-${col.id}`}
|
||||
value={isVisible}
|
||||
onChange={(): void => handleToggle(col.id, !isVisible)}
|
||||
/>
|
||||
|
||||
@@ -22,13 +22,14 @@ export function VirtuosoTableColGroup<TData>({
|
||||
{visibleTanstackColumns.map((tanstackCol, index) => {
|
||||
const colDef = columnDefsById.get(tanstackCol.id);
|
||||
if (!colDef) {
|
||||
return <col key={tanstackCol.id} />;
|
||||
return <col key={tanstackCol.id} data-testid="tanstack-col" />;
|
||||
}
|
||||
const persistedWidth = columnSizing[tanstackCol.id];
|
||||
const isLastColumn = index === fillColumnIndex;
|
||||
return (
|
||||
<col
|
||||
key={tanstackCol.id}
|
||||
data-testid="tanstack-col"
|
||||
style={getColumnWidthStyle(colDef, persistedWidth, isLastColumn)}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -22,7 +22,7 @@ jest.mock('../TanStackTableStateContext', () => ({
|
||||
useClearRowHovered: (_rowId: string): (() => void) => mockClearRowHovered,
|
||||
}));
|
||||
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
|
||||
import TanStackCustomTableRow from '../TanStackCustomTableRow';
|
||||
import type { FlatItem, TableRowContext } from '../types';
|
||||
@@ -73,7 +73,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
...baseContext,
|
||||
isRowActive: (row) => row.id === '1',
|
||||
};
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -84,7 +84,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).toHaveClass('tableRowActive');
|
||||
expect(screen.getByRole('row')).toHaveClass('tableRowActive');
|
||||
});
|
||||
|
||||
it('does not apply active class when isRowActive returns false', () => {
|
||||
@@ -92,7 +92,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
...baseContext,
|
||||
isRowActive: (row) => row.id === 'other',
|
||||
};
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -103,7 +103,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).not.toHaveClass('tableRowActive');
|
||||
expect(screen.getByRole('row')).not.toHaveClass('tableRowActive');
|
||||
});
|
||||
|
||||
it('renders expansion row with expansion class', () => {
|
||||
@@ -111,7 +111,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
kind: 'expansion',
|
||||
row: { original: { id: '1' }, id: '1' } as never,
|
||||
};
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -122,12 +122,12 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
expect(container.querySelector('tr')).toHaveClass('tableRowExpansion');
|
||||
expect(screen.getByRole('row')).toHaveClass('tableRowExpansion');
|
||||
});
|
||||
|
||||
describe('hover state management', () => {
|
||||
it('calls setRowHovered on mouse enter', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -138,13 +138,13 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
fireEvent.mouseEnter(row);
|
||||
expect(mockSetRowHovered).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls clearRowHovered on mouse leave', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -155,7 +155,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
fireEvent.mouseLeave(row);
|
||||
expect(mockClearRowHovered).toHaveBeenCalled();
|
||||
});
|
||||
@@ -163,7 +163,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
|
||||
describe('virtuoso integration', () => {
|
||||
it('forwards data-index attribute to tr element', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -174,12 +174,12 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
expect(row).toHaveAttribute('data-index', '0');
|
||||
});
|
||||
|
||||
it('forwards data-item-index attribute to tr element', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -190,12 +190,12 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
expect(row).toHaveAttribute('data-item-index', '0');
|
||||
});
|
||||
|
||||
it('forwards data-known-size attribute to tr element', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -206,7 +206,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
expect(row).toHaveAttribute('data-known-size', '40');
|
||||
});
|
||||
});
|
||||
@@ -217,7 +217,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
...baseContext,
|
||||
getRowStyle: () => ({ backgroundColor: 'red' }),
|
||||
};
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -228,7 +228,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
expect(row).toHaveStyle({ backgroundColor: 'red' });
|
||||
});
|
||||
|
||||
@@ -237,7 +237,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
...baseContext,
|
||||
getRowClassName: () => 'custom-row-class',
|
||||
};
|
||||
const { container } = render(
|
||||
render(
|
||||
<table>
|
||||
<tbody>
|
||||
<TanStackCustomTableRow
|
||||
@@ -248,7 +248,7 @@ describe('TanStackCustomTableRow', () => {
|
||||
</tbody>
|
||||
</table>,
|
||||
);
|
||||
const row = container.querySelector('tr')!;
|
||||
const row = screen.getByRole('row');
|
||||
expect(row).toHaveClass('custom-row-class');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { screen } from '@testing-library/react';
|
||||
import { screen, within } from 'tests/test-utils';
|
||||
|
||||
import type { TableColumnDef } from '../types';
|
||||
import { defaultColumns, renderTanStackTable, type TestRow } from './testUtils';
|
||||
@@ -14,38 +14,35 @@ const actionsColumn: TableColumnDef<TestRow> = {
|
||||
width: { fixed: '96px', passLastColumnFill: true },
|
||||
};
|
||||
|
||||
const colWidths = (container: HTMLElement): string[] =>
|
||||
Array.from(container.querySelectorAll('colgroup col')).map(
|
||||
(col) => (col as HTMLElement).style.width,
|
||||
);
|
||||
const colWidths = (): string[] =>
|
||||
screen.getAllByTestId('tanstack-col').map((col) => col.style.width);
|
||||
|
||||
const isResizable = (headerText: string): boolean =>
|
||||
const isResizable = (columnId: string): boolean =>
|
||||
Boolean(
|
||||
screen
|
||||
.getByText(headerText)
|
||||
.closest('th')
|
||||
?.querySelector('[title="Drag to resize column"]'),
|
||||
within(screen.getByTestId(`tanstack-header-${columnId}`)).queryByTitle(
|
||||
'Drag to resize column',
|
||||
),
|
||||
);
|
||||
|
||||
describe('TanStackTable column fill', () => {
|
||||
it('fills and locks the last column by default', () => {
|
||||
const { container } = renderTanStackTable();
|
||||
renderTanStackTable();
|
||||
|
||||
expect(colWidths(container).at(-1)).toBe('100%');
|
||||
expect(isResizable('Name')).toBe(true);
|
||||
expect(isResizable('Value')).toBe(false);
|
||||
expect(colWidths().at(-1)).toBe('100%');
|
||||
expect(isResizable('name')).toBe(true);
|
||||
expect(isResizable('value')).toBe(false);
|
||||
});
|
||||
|
||||
it('hands the fill to the previous column when the last passes it on', () => {
|
||||
const { container } = renderTanStackTable({
|
||||
renderTanStackTable({
|
||||
props: { columns: [...defaultColumns, actionsColumn] },
|
||||
});
|
||||
|
||||
const widths = colWidths(container);
|
||||
const widths = colWidths();
|
||||
expect(widths.at(-2)).toBe('100%');
|
||||
expect(widths.at(-1)).toBe('96px');
|
||||
expect(isResizable('Name')).toBe(true);
|
||||
expect(isResizable('Value')).toBe(false);
|
||||
expect(isResizable('Actions')).toBe(false);
|
||||
expect(isResizable('name')).toBe(true);
|
||||
expect(isResizable('value')).toBe(false);
|
||||
expect(isResizable('actions')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {
|
||||
fireEvent,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
import { UrlUpdateEvent } from 'nuqs/adapters/testing';
|
||||
|
||||
import TanStackTable from '../index';
|
||||
@@ -159,14 +164,7 @@ describe('TanStackTableView Integration', () => {
|
||||
});
|
||||
|
||||
// Find page 2 button/link within pagination navigation
|
||||
const nav = screen.getByRole('navigation');
|
||||
const page2 = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
if (!page2) {
|
||||
throw new Error('Page 2 button not found in pagination');
|
||||
}
|
||||
await user.click(page2);
|
||||
await user.click(screen.getByTestId('pagination-page-2'));
|
||||
|
||||
await waitFor(() => {
|
||||
const lastPage = onUrlUpdate.mock.calls
|
||||
@@ -327,9 +325,7 @@ describe('TanStackTableView Integration', () => {
|
||||
});
|
||||
|
||||
// Page size combobox trigger should be visible by default (button with aria-haspopup)
|
||||
const comboboxTrigger = document.querySelector(
|
||||
'button[aria-haspopup="dialog"]',
|
||||
);
|
||||
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
|
||||
expect(comboboxTrigger).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -349,9 +345,7 @@ describe('TanStackTableView Integration', () => {
|
||||
expect(screen.getByRole('navigation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const comboboxTrigger = document.querySelector(
|
||||
'button[aria-haspopup="dialog"]',
|
||||
);
|
||||
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
|
||||
expect(comboboxTrigger).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -371,9 +365,7 @@ describe('TanStackTableView Integration', () => {
|
||||
expect(screen.getByRole('navigation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const comboboxTrigger = document.querySelector(
|
||||
'button[aria-haspopup="dialog"]',
|
||||
);
|
||||
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
|
||||
expect(comboboxTrigger).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -391,14 +383,7 @@ describe('TanStackTableView Integration', () => {
|
||||
expect(screen.getByRole('navigation')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const nav = screen.getByRole('navigation');
|
||||
const page2 = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
if (!page2) {
|
||||
throw new Error('Page 2 button not found in pagination');
|
||||
}
|
||||
await user.click(page2);
|
||||
await user.click(screen.getByTestId('pagination-page-2'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onPageChange).toHaveBeenCalledWith(2);
|
||||
@@ -420,15 +405,7 @@ describe('TanStackTableView Integration', () => {
|
||||
},
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
document.querySelector('button[aria-haspopup="dialog"]'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const comboboxTrigger = document.querySelector(
|
||||
'button[aria-haspopup="dialog"]',
|
||||
) as HTMLElement;
|
||||
const comboboxTrigger = await screen.findByTestId('pagination-page-size');
|
||||
await user.click(comboboxTrigger);
|
||||
|
||||
// Select a different page size option
|
||||
@@ -476,14 +453,7 @@ describe('TanStackTableView Integration', () => {
|
||||
});
|
||||
|
||||
// Navigate to page 2
|
||||
const nav = screen.getByRole('navigation');
|
||||
const page2 = Array.from(nav.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.trim() === '2',
|
||||
);
|
||||
if (!page2) {
|
||||
throw new Error('Page 2 button not found in pagination');
|
||||
}
|
||||
await user.click(page2);
|
||||
await user.click(screen.getByTestId('pagination-page-2'));
|
||||
|
||||
await waitFor(() => {
|
||||
const lastPage = onUrlUpdate.mock.calls
|
||||
@@ -494,10 +464,7 @@ describe('TanStackTableView Integration', () => {
|
||||
});
|
||||
|
||||
// Change page size
|
||||
const comboboxTrigger = document.querySelector(
|
||||
'button[aria-haspopup="dialog"]',
|
||||
) as HTMLElement;
|
||||
await user.click(comboboxTrigger);
|
||||
await user.click(screen.getByTestId('pagination-page-size'));
|
||||
|
||||
await user.type(
|
||||
await screen.findByTestId('pagination-page-size-search'),
|
||||
@@ -687,6 +654,7 @@ describe('TanStackTableView Integration', () => {
|
||||
renderTanStackTable({
|
||||
props: {
|
||||
isRowActive: (row) => row.id === '1',
|
||||
getRowTestId: (row) => `row-${row.id}`,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -695,9 +663,7 @@ describe('TanStackTableView Integration', () => {
|
||||
});
|
||||
|
||||
// Find the row containing Item 1 and check for active class
|
||||
const cell = screen.getByText('Item 1');
|
||||
const row = cell.closest('tr');
|
||||
expect(row).toHaveClass('tableRowActive');
|
||||
expect(screen.getByTestId('row-1')).toHaveClass('tableRowActive');
|
||||
});
|
||||
|
||||
it('calls onRowClick with isActive: true when clicking the active row', async () => {
|
||||
@@ -844,8 +810,8 @@ describe('TanStackTableView Integration', () => {
|
||||
expect(screen.getByText('Expanded: Item 1')).toBeInTheDocument();
|
||||
|
||||
// Verify all 3 data rows plus 1 expansion row = 4 tr elements in tbody
|
||||
const tbody = screen.getByRole('table').querySelector('tbody');
|
||||
expect(tbody?.querySelectorAll('tr')).toHaveLength(4);
|
||||
const [, tbody] = within(screen.getByRole('table')).getAllByRole('rowgroup');
|
||||
expect(within(tbody).getAllByRole('row')).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -996,7 +962,9 @@ describe('TanStackTableView Integration', () => {
|
||||
|
||||
describe('hasSingleColumn — gates the Remove popover per-column', () => {
|
||||
const hasSingleColumnFlagPresent = (): boolean =>
|
||||
Boolean(document.querySelector('th[data-single-column="true"]'));
|
||||
screen
|
||||
.getAllByTestId(/^tanstack-header-/)
|
||||
.some((th) => th.getAttribute('data-single-column') === 'true');
|
||||
|
||||
it('is true when only one non-pinned column exists', async () => {
|
||||
renderTanStackTable({
|
||||
|
||||
@@ -21,6 +21,7 @@ export default function TypicalOverlayScrollbar({
|
||||
options={options}
|
||||
style={style}
|
||||
className="overlay-scrollbar"
|
||||
data-testid="overlay-scrollbar"
|
||||
data-overlayscrollbars-initialize
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { screen } from '@testing-library/react';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import ValueGraph from '../index';
|
||||
import { getBackgroundColorAndThresholdCheck } from '../utils';
|
||||
@@ -95,12 +94,11 @@ describe('ValueGraph', () => {
|
||||
isConflictingThresholds: false,
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<ValueGraph value="42" rawValue={42} thresholds={[]} />,
|
||||
);
|
||||
render(<ValueGraph value="42" rawValue={42} thresholds={[]} />);
|
||||
|
||||
const containerElement = container.querySelector('.value-graph-container');
|
||||
expect(containerElement).toHaveStyle({ backgroundColor: 'blue' });
|
||||
expect(screen.getByTestId('value-graph-container')).toHaveStyle({
|
||||
backgroundColor: 'blue',
|
||||
});
|
||||
});
|
||||
|
||||
it('displays conflicting thresholds indicator when multiple thresholds match', () => {
|
||||
|
||||
@@ -92,6 +92,7 @@ function ValueGraph({
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="value-graph-container"
|
||||
data-testid="value-graph-container"
|
||||
style={{
|
||||
backgroundColor:
|
||||
threshold.thresholdFormat === 'Background'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { YAxisCategoryNames } from '../constants';
|
||||
import { UniversalYAxisUnit, YAxisSource } from '../types';
|
||||
@@ -13,7 +12,7 @@ describe('YAxisUnitSelector', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnChange.mockClear();
|
||||
user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
user = userEvent.setup();
|
||||
});
|
||||
|
||||
it('renders with default placeholder', () => {
|
||||
|
||||
@@ -111,7 +111,7 @@ describe('CmdKPalette', () => {
|
||||
});
|
||||
|
||||
it('clicking a navigation item navigates to the correct route', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<CmdKPalette userRole="ADMIN" />);
|
||||
|
||||
await user.type(
|
||||
@@ -148,7 +148,7 @@ describe('CmdKPalette', () => {
|
||||
});
|
||||
|
||||
it('closing the palette via handleInvoke sets open to false', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<CmdKPalette userRole="ADMIN" />);
|
||||
|
||||
await user.type(
|
||||
|
||||
@@ -144,6 +144,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
<div
|
||||
className={styles.backdrop}
|
||||
role="dialog"
|
||||
data-testid="ai-assistant-modal"
|
||||
aria-modal="true"
|
||||
aria-label="Noz"
|
||||
onClick={handleBackdropClick}
|
||||
|
||||
@@ -29,7 +29,7 @@ describe('ActionsSection open_resource', () => {
|
||||
'/alerts/edit?ruleId=rule-1&tab=1',
|
||||
'/alerts/overview?ruleId=rule-1&relativeTime=6h',
|
||||
])('disables Open alert while that alert is open at %s', async (route) => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ActionsSection actions={[OPEN_ALERT]} messageId="message-1" />,
|
||||
undefined,
|
||||
@@ -51,7 +51,7 @@ describe('ActionsSection open_resource', () => {
|
||||
it.each(['/alerts/edit?ruleId=rule-2', '/alerts/history?ruleId=rule-1'])(
|
||||
'opens the alert from %s',
|
||||
async (route) => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ActionsSection actions={[OPEN_ALERT]} messageId="message-2" />,
|
||||
undefined,
|
||||
|
||||
@@ -138,7 +138,7 @@ describe('ActionsSection rollback chip', () => {
|
||||
|
||||
describe('ActionsSection apply_filter', () => {
|
||||
it('opens the explorer in the Table view when the chip is clicked from another page', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[countByServiceAction('Open in Logs Explorer')]}
|
||||
@@ -159,7 +159,7 @@ describe('ActionsSection apply_filter', () => {
|
||||
});
|
||||
|
||||
it('opens the explorer on the time range that produced the answer', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[
|
||||
|
||||
@@ -17,7 +17,7 @@ const steps: ActivityItem[] = [
|
||||
|
||||
describe('ActivityGroup', () => {
|
||||
it('names the running step and opens the steps so far on request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<ActivityGroup items={steps} isLive />);
|
||||
|
||||
const toggle = screen.getByTestId('ai-activity-toggle');
|
||||
@@ -35,7 +35,7 @@ describe('ActivityGroup', () => {
|
||||
});
|
||||
|
||||
it('folds a finished run behind its step count', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<ActivityGroup items={steps} />);
|
||||
|
||||
const toggle = screen.getByTestId('ai-activity-toggle');
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
@use '../../_scrollbar' as *;
|
||||
|
||||
.card {
|
||||
// The modal and panel portal outside the layout's border-box reset.
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: var(--spacing-6);
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('ComposerCaret', () => {
|
||||
});
|
||||
|
||||
it('draws its caret while the composer has focus', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<Composer />);
|
||||
|
||||
await user.click(screen.getByTestId('composer'));
|
||||
@@ -63,7 +63,7 @@ describe('ComposerCaret', () => {
|
||||
});
|
||||
|
||||
it('hides its caret once the composer loses focus', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<Composer />);
|
||||
await user.click(screen.getByTestId('composer'));
|
||||
|
||||
@@ -73,7 +73,7 @@ describe('ComposerCaret', () => {
|
||||
});
|
||||
|
||||
it('hides its caret while text is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<Composer />);
|
||||
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
|
||||
await user.type(composer, 'checkout latency');
|
||||
@@ -86,7 +86,7 @@ describe('ComposerCaret', () => {
|
||||
});
|
||||
|
||||
it('moves its caret when code changes the text', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<Composer />);
|
||||
await user.type(screen.getByTestId('composer'), 'checkout');
|
||||
expect(screen.getByTestId('ai-composer-caret')).toHaveStyle({
|
||||
@@ -101,7 +101,7 @@ describe('ComposerCaret', () => {
|
||||
});
|
||||
|
||||
it('hides its caret once the composer scrolls it out of view', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(<Composer />);
|
||||
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
|
||||
await user.type(composer, 'checkout latency');
|
||||
|
||||
@@ -45,6 +45,7 @@ export default function ContextPickerEmptyState({
|
||||
return (
|
||||
<div
|
||||
className={styles.contextPopoverEmpty}
|
||||
data-testid={`ai-context-empty-${category}`}
|
||||
style={{ '--empty-accent': CATEGORY_ACCENT[category] } as CSSProperties}
|
||||
>
|
||||
<span className={styles.contextPopoverEmptyIcon} aria-hidden="true">
|
||||
|
||||
@@ -26,7 +26,7 @@ describe('ChatInput composer', () => {
|
||||
});
|
||||
|
||||
it('lets the user type but not send while sending is blocked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSend = jest.fn() as jest.MockedFunction<
|
||||
ComponentProps<typeof ChatInput>['onSend']
|
||||
>;
|
||||
|
||||
@@ -12,7 +12,7 @@ const serviceContext: MessageContext = {
|
||||
|
||||
describe('ChatInput — context pills', () => {
|
||||
it('names a page context by its type and drops it on remove', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onDismissAutoContext = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<ComponentProps<typeof ChatInput>['onDismissAutoContext']>
|
||||
>;
|
||||
|
||||
@@ -7,15 +7,15 @@ function renderEmptyState(
|
||||
category: ContextCategory,
|
||||
query: string,
|
||||
onPrefill = jest.fn(),
|
||||
): { onPrefill: jest.Mock; container: HTMLElement } {
|
||||
const { container } = render(
|
||||
): { onPrefill: jest.Mock } {
|
||||
render(
|
||||
<ContextPickerEmptyState
|
||||
category={category}
|
||||
query={query}
|
||||
onPrefill={onPrefill}
|
||||
/>,
|
||||
);
|
||||
return { onPrefill, container };
|
||||
return { onPrefill };
|
||||
}
|
||||
|
||||
function ctaFor(category: ContextCategory): HTMLElement {
|
||||
@@ -122,9 +122,12 @@ describe('ContextPickerEmptyState', () => {
|
||||
['Alerts', 'var(--accent-cherry)'],
|
||||
['Services', 'var(--accent-forest)'],
|
||||
])('maps %s to the semantic accent %s', (category, accent) => {
|
||||
const { container } = renderEmptyState(category, '');
|
||||
const root = container.firstChild as HTMLElement;
|
||||
expect(root.style.getPropertyValue('--empty-accent')).toBe(accent);
|
||||
renderEmptyState(category, '');
|
||||
expect(
|
||||
screen
|
||||
.getByTestId(`ai-context-empty-${category}`)
|
||||
.style.getPropertyValue('--empty-accent'),
|
||||
).toBe(accent);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
.clarification {
|
||||
// The modal and panel portal outside the layout's border-box reset.
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
padding: var(--spacing-6);
|
||||
|
||||
@@ -69,16 +69,14 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
background: var(--l2-background);
|
||||
color: var(--l1-foreground);
|
||||
font-size: var(--paragraph-base-400-font-size);
|
||||
border-bottom-left-radius: var(--radius-2);
|
||||
}
|
||||
|
||||
// The full page shows replies as plain text on the pane; errors keep their callout.
|
||||
// The full page sets replies flush on the pane; errors keep their callout.
|
||||
.assistant .fullPage &:not(.error) {
|
||||
padding: 0 0 0 var(--spacing-5);
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('EmptyState', () => {
|
||||
});
|
||||
|
||||
it('sends a suggestion when it is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onSend = jest.fn();
|
||||
mockChips.mockReturnValue({
|
||||
chips: [{ id: 'slow_queries', text: 'Find slow database queries' }],
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider, useSelector } from 'react-redux';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import {
|
||||
fireEvent,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
@@ -141,6 +148,7 @@ describe('Exceptions - All Errors', () => {
|
||||
|
||||
describe('pagination edge cases', () => {
|
||||
it('should navigate to page 2 when pageSize=100 and clicking next', async () => {
|
||||
const user = userEvent.setup();
|
||||
// Arrange: start with pageSize=100 and offset=0
|
||||
render(
|
||||
<Exceptions initUrl="/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName" />,
|
||||
@@ -149,11 +157,7 @@ describe('Exceptions - All Errors', () => {
|
||||
// Wait for initial load
|
||||
await screen.findByText(/redis timeout/i);
|
||||
|
||||
const nextPageItem = screen.getByTitle('Next Page');
|
||||
const nextPageButton = nextPageItem.querySelector(
|
||||
'button',
|
||||
) as HTMLButtonElement;
|
||||
fireEvent.click(nextPageButton);
|
||||
await user.click(within(screen.getByTitle('Next Page')).getByRole('button'));
|
||||
|
||||
await waitFor(() => {
|
||||
const qp = new URLSearchParams(window.location.search);
|
||||
@@ -170,22 +174,20 @@ describe('Exceptions - All Errors', () => {
|
||||
<Exceptions initUrl="/exceptions?pageSize=100&offset=100&order=ascending&orderParam=serviceName" />,
|
||||
);
|
||||
await screen.findByText(/redis timeout/i);
|
||||
const activeItem = document.querySelector('.ant-pagination-item-active');
|
||||
expect(activeItem?.textContent).toBe('2');
|
||||
expect(screen.getByTitle('2')).toHaveClass('ant-pagination-item-active');
|
||||
const qp = new URLSearchParams(window.location.search);
|
||||
expect(qp.get('pageSize')).toBe('100');
|
||||
expect(qp.get('offset')).toBe('100');
|
||||
});
|
||||
|
||||
it('clicking a numbered page updates offset correctly', async () => {
|
||||
const user = userEvent.setup();
|
||||
// pageSize=100, click page 3 => offset = 200
|
||||
render(
|
||||
<Exceptions initUrl="/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName" />,
|
||||
);
|
||||
await screen.findByText(/redis timeout/i);
|
||||
const page3Item = screen.getByTitle('3');
|
||||
const page3Anchor = page3Item.querySelector('a') as HTMLAnchorElement;
|
||||
fireEvent.click(page3Anchor);
|
||||
await user.click(within(screen.getByTitle('3')).getByText('3'));
|
||||
await waitFor(() => {
|
||||
const qp = new URLSearchParams(window.location.search);
|
||||
expect(qp.get('offset')).toBe('200');
|
||||
|
||||
@@ -191,7 +191,8 @@ function TopErrors({
|
||||
rowClassName={(_, index): string =>
|
||||
index % 2 === 0 ? 'table-row-dark' : 'table-row-light'
|
||||
}
|
||||
onRow={(record): { onClick: () => void } => ({
|
||||
onRow={(record): { 'data-testid': string; onClick: () => void } => ({
|
||||
'data-testid': `top-errors-row-${record.endpointName}-${record.statusCode}`,
|
||||
onClick: (): void => {
|
||||
const filters = getTopErrorsCoRelationQueryFilters(
|
||||
domainName,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
import { TraceAggregation } from 'api/v5/v5';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
@@ -204,10 +204,7 @@ describe('DomainMetrics - V5 Query Payload Tests', () => {
|
||||
renderComponent();
|
||||
|
||||
// Wait for skeletons to disappear
|
||||
await waitFor(() => {
|
||||
const skeletons = document.querySelectorAll('.ant-skeleton-button');
|
||||
expect(skeletons).toHaveLength(0);
|
||||
});
|
||||
await screen.findByText('150');
|
||||
|
||||
// Verify all metric labels are displayed
|
||||
expect(screen.getByText('EXTERNAL API')).toBeInTheDocument();
|
||||
@@ -243,13 +240,8 @@ describe('DomainMetrics - V5 Query Payload Tests', () => {
|
||||
|
||||
renderComponent();
|
||||
|
||||
await waitFor(() => {
|
||||
const skeletons = document.querySelectorAll('.ant-skeleton-button');
|
||||
expect(skeletons).toHaveLength(0);
|
||||
});
|
||||
|
||||
// When no data, all values should show "-"
|
||||
const dashValues = screen.getAllByText('-');
|
||||
const dashValues = await screen.findAllByText('-');
|
||||
expect(dashValues.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user