Compare commits

..

1 Commits

Author SHA1 Message Date
Ashwin Bhatkal
0c9800fb9b ci(goci): bump setup-go to v7 to reuse main's module cache 2026-11-25 01:19:25 +05:30
443 changed files with 2946 additions and 8279 deletions

View File

@@ -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`. `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.
- **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.
- **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__`.

View File

@@ -63,7 +63,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: check-semconv-generated-files
@@ -78,7 +78,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: qemu-install
@@ -114,7 +114,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-openapi
@@ -131,7 +131,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-authz
@@ -148,7 +148,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-web-settings
@@ -165,7 +165,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-transaction-groups

View File

@@ -296,8 +296,6 @@
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
"signoz/no-direct-react-router-import": "error",
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
"signoz/no-builder-ai-query-access": "error",
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -554,7 +552,6 @@
],
"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,
@@ -562,8 +559,6 @@
"no-restricted-globals": "off",
// Tests need raw localStorage/sessionStorage to seed DOM state for isolation
"signoz/no-zustand-getstate-in-hooks": "off",
"signoz/no-builder-ai-query-access": "off",
// Fixtures build and assert on the raw AI slot
"@typescript-eslint/no-explicit-any": "off", // Tests often need any for mocks/stubs
"@typescript-eslint/explicit-module-boundary-types": "off", // Return types not required in tests
"@typescript-eslint/explicit-function-return-type": "off" // Same as above rule, don't need to care about return type
@@ -620,20 +615,6 @@
"rules": {
"signoz/no-direct-react-router-import": "off"
}
},
{
// builderSlot owns the AI slot; the rest normalise its wire shape or test whether it exists, which the helpers hide
"files": [
"src/lib/query/builderSlot.ts",
"src/hooks/queryBuilder/normalizeCompositeQuery.ts",
"src/hooks/queryBuilder/useGetCompositeQueryParam.ts",
"src/providers/QueryBuilder.tsx",
"src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelKindChange.ts",
"src/pages/DashboardPage/DashboardContainer/Panels/utils/seedBuilderForMode.ts"
],
"rules": {
"signoz/no-builder-ai-query-access": "off"
}
}
]
}

View File

@@ -21,7 +21,7 @@ import i18n from '../src/ReactI18';
// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
// not report because the requests look like static assets.
import '../src/lib/monaco/loader';
import '../src/lib/monaco/setup';
import '../src/styles.scss';
@@ -176,7 +176,6 @@ const preview: Preview = {
'AI Observability',
['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
'Noz',
['Overview', 'Modal', 'Panel'],
'Metering',
['Cost Meter', 'Usage Explorer'],
'Messaging Queues',

View File

@@ -11,7 +11,7 @@ const config: Config.InitialOptions = {
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
modulePathIgnorePatterns: ['dist'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'<rootDir>/__mocks__/fileMock.ts',

View File

@@ -1,59 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message =
'from lib/query/builderSlot instead of accessing builder_ai_query';
await ruleTester({
rule: 'no-builder-ai-query-access',
valid: [
{
name: 'reading through the slot helper',
code: 'export const data = getActiveBuilder(query).queryData;',
},
{
name: 'reading the builder slot',
code: 'export const data = query.builder.queryData;',
},
{
name: 'building a query with the AI slot',
code: 'export const next = { ...query, builder_ai_query: builder };',
},
{
name: 'generated enum member',
code:
'export const type = Querybuildertypesv5QueryTypeDTO.builder_ai_query;',
},
{
name: 'type position',
code: "export type Slot = Query['builder_ai_query'];",
},
],
invalid: [
{
name: 'picking the slot by query type',
code:
'export const data =\n\tquery.queryType === EQueryType.AI_QUERY_BUILDER\n\t\t? query.builder_ai_query?.queryData\n\t\t: query.builder.queryData;',
errors: [{ message, line: 3 }],
},
{
name: 'optional chaining',
code: 'export const slot = query?.builder_ai_query;',
errors: [{ message, line: 1 }],
},
{
name: 'writing the slot',
code: 'query.builder_ai_query = builder;',
errors: [{ message, line: 1 }],
},
{
name: 'bracket access',
code: "export const slot = query['builder_ai_query'];",
errors: [{ message, line: 1 }],
},
{
name: 'destructuring',
code: 'export const { builder_ai_query: slot } = query;',
errors: [{ message, line: 1 }],
},
],
});

View File

@@ -1,60 +0,0 @@
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 }],
},
],
});

View File

@@ -1,51 +0,0 @@
const SLOT = 'builder_ai_query';
function isSlotKey(key, computed) {
if (key.type === 'Literal') {
return key.value === SLOT;
}
return !computed && key.type === 'Identifier' && key.name === SLOT;
}
// Generated enums like Querybuildertypesv5QueryTypeDTO.builder_ai_query are not queries
function isGeneratedEnum(object) {
return object.type === 'Identifier' && /^[A-Z]/.test(object.name);
}
export default {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow direct builder_ai_query access; use the lib/query/builderSlot helpers',
category: 'Query Builder',
},
schema: [],
messages: {
useSlotHelper:
'Use getActiveBuilder, getBuilderBySlotKey or replaceBuilderBySlotKey from lib/query/builderSlot instead of accessing builder_ai_query directly.',
},
},
create(context) {
return {
MemberExpression(node) {
if (
isSlotKey(node.property, node.computed) &&
!isGeneratedEnum(node.object)
) {
context.report({ node, messageId: 'useSlotHelper' });
}
},
ObjectPattern(node) {
node.properties.forEach((property) => {
if (
property.type === 'Property' &&
isSlotKey(property.key, property.computed)
) {
context.report({ node: property, messageId: 'useSlotHelper' });
}
});
},
};
},
};

View File

@@ -1,60 +0,0 @@
/**
* 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}\`.`,
});
}
},
};
},
};

View File

@@ -19,8 +19,6 @@ 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';
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
export default {
meta: {
@@ -41,7 +39,5 @@ export default {
'no-direct-react-router-import': noDirectReactRouterImport,
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
'no-dom-node-access': noDomNodeAccess,
'no-builder-ai-query-access': noBuilderAiQueryAccess,
},
};

View File

@@ -117,8 +117,6 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -121,8 +121,6 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -17,11 +17,13 @@ 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();
});

View File

@@ -15,11 +15,13 @@ 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();
});

View File

@@ -1,4 +1,4 @@
import { act, render, screen } from 'tests/test-utils';
import { act, render, screen } from '@testing-library/react';
import LabelColumn from './LabelColumn';
@@ -92,9 +92,7 @@ describe('LabelColumn', () => {
renderWithProviders(<LabelColumn labels={labels} />);
const isHidden = (label: string): boolean =>
screen
.getByTestId(`label-tag-container-${label}`)
.classList.contains('overflowed');
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
@@ -159,7 +157,8 @@ describe('LabelColumn', () => {
it('should render empty when no labels provided', () => {
renderWithProviders(<LabelColumn labels={[]} />);
expect(screen.getByTestId('label-column')).toBeEmptyDOMElement();
const column = screen.getByTestId('label-column');
expect(column.children).toHaveLength(0);
});
it('should use primary color by default', () => {

View File

@@ -45,7 +45,7 @@ function LabelTag({
</div>
}
>
<span className={className} data-testid={`label-tag-container-${label}`}>
<span className={className}>
<Badge
textTransform="none"
color={color ?? 'secondary'}

View File

@@ -22,10 +22,7 @@ function AppLoading(): JSX.Element {
const isDarkMode = getThemeFromStorage();
return (
<div
className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}
data-testid="app-loading-container"
>
<div className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}>
<div className="perilin-bg" />
<div className="app-loading-content">
<div className="brand">
@@ -56,7 +53,7 @@ function AppLoading(): JSX.Element {
</Typography>
</div>
<div className="loader" data-testid="app-loading-loader" />
<div className="loader" />
</div>
</div>
);

View File

@@ -1,5 +1,4 @@
import { render } from '@testing-library/react';
import { screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import getLocal from '../../../api/browser/localstorage/get';
import AppLoading from '../AppLoading';
@@ -16,6 +15,7 @@ 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.getByTestId('app-loading-container');
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
expect(container).toHaveClass('dark');
expect(container).not.toHaveClass('lightMode');
});
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
expect(tagline).toBeInTheDocument();
// Check for loader
const loader = screen.getByTestId('app-loading-loader');
const loader = document.querySelector('.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.getByTestId('app-loading-container');
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
expect(container).toHaveClass('dark');
});
});

View File

@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
});
it('submit button becomes disabled after clearing the name field', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');

View File

@@ -1,6 +1,5 @@
import { useState } from 'react';
import { render } from '@testing-library/react';
import { fireEvent, screen, userEvent } from 'tests/test-utils';
import { fireEvent, render, screen } from '@testing-library/react';
import dayjs from 'dayjs';
import { mockAppLocation } from 'tests/router-mocks';
import * as timeUtils from 'utils/timeUtils';
@@ -158,8 +157,7 @@ describe('CustomTimePicker', () => {
expect(onValid).not.toHaveBeenCalled();
});
it('treats close after change like pressing Enter (blur + chevron)', async () => {
const user = userEvent.setup();
it('treats close after change like pressing Enter (blur + chevron)', () => {
const onValid = jest.fn();
const onError = jest.fn();
@@ -168,13 +166,16 @@ describe('CustomTimePicker', () => {
const input = screen.getByRole('textbox');
// Open and change value so "changed since open" is true
await user.click(input);
await user.clear(input);
await user.type(input, '5m');
await user.tab();
fireEvent.focus(input);
fireEvent.change(input, { target: { value: '5m' } });
fireEvent.blur(input);
// Click the chevron (which triggers handleClose)
await user.click(screen.getByTestId('time-picker-close-chevron'));
const chevron = document.querySelector(
'.time-input-suffix-icon-badge',
) as HTMLElement;
fireEvent.click(chevron);
// Should have applied the value (same as Enter)
expect(onValid).toHaveBeenCalledTimes(1);

View File

@@ -640,14 +640,12 @@ 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>

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
@@ -925,7 +925,7 @@ describe('EditMemberDrawer', () => {
});
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockToast = jest.mocked(toast);
renderDrawer();

View File

@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
// Click the close button
const closeButton = screen.getByTestId('close-button');
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(triggerButton);
// Check if the modal is displayed
@@ -165,13 +165,12 @@ 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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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'));
@@ -181,6 +180,8 @@ it('should close the modal when the onCancel event is triggered', async () => {
await waitFor(() => {
// check if the modal is not visible
expect(modal).toHaveStyle({ display: 'none' });
const modal = document.getElementsByClassName('ant-modal');
const style = window.getComputedStyle(modal[0]);
expect(style.display).toBe('none');
});
});

View File

@@ -1,6 +1,6 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { act, render, renderHook } from 'tests/test-utils';
import { act, render, renderHook } from '@testing-library/react';
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 { asFragment } = render(
const { container } = render(
<Provider store={store}>
<GlobalTimeStoreAdapter />
</Provider>,
);
expect(asFragment().hasChildNodes()).toBe(false);
expect(container.firstChild).toBeNull();
});
it('should sync relative time from Redux to Zustand store', () => {

View File

@@ -2,14 +2,8 @@ import { Typography } from '@signozhq/ui/typography';
function AnnouncementsModal(): JSX.Element {
return (
<div
className="announcements-modal-container"
data-testid="announcements-modal"
>
<div
className="announcements-modal-container-header"
data-testid="announcements-modal-header"
>
<div className="announcements-modal-container">
<div className="announcements-modal-container-header">
<Typography
variant="paragraph"
size="base"

View File

@@ -1,4 +1,4 @@
import { render, screen, within } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import AnnouncementsModal from '../AnnouncementsModal';
@@ -12,14 +12,15 @@ describe('AnnouncementsModal', () => {
it('should have proper structure and classes', () => {
render(<AnnouncementsModal />);
const container = screen.getByTestId('announcements-modal');
expect(container).toHaveClass('announcements-modal-container');
const container = screen
.getByText('Announcements')
.closest('.announcements-modal-container');
expect(container).toBeInTheDocument();
const headerContainer = within(container).getByTestId(
'announcements-modal-header',
);
expect(headerContainer).toHaveClass('announcements-modal-container-header');
expect(headerContainer).toHaveTextContent('Announcements');
const headerContainer = screen
.getByText('Announcements')
.closest('.announcements-modal-container-header');
expect(headerContainer).toBeInTheDocument();
});
it('should render without any errors', () => {

View File

@@ -64,10 +64,7 @@ function InviteMembers({
const hasSuccesses = successResults.length > 0;
return (
<div
className={cx(styles.inviteMembers, className)}
data-testid="invite-members"
>
<div className={cx(styles.inviteMembers, className)}>
<div className={styles.table}>
{showHeader && (
<div className={styles.header}>

View File

@@ -66,9 +66,9 @@ describe('InviteMembers - Rendering', () => {
});
it('applies custom className', () => {
render(<InviteMembers className="custom-class" />);
const { container } = render(<InviteMembers className="custom-class" />);
expect(screen.getByTestId('invite-members')).toHaveClass('custom-class');
expect(container.querySelector('.custom-class')).toBeInTheDocument();
});
it('renders footer via renderFooter prop', () => {

View File

@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
});
it('adds a row when "Add another" is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={3} />);
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
});
it('respects minRows constraint when removing rows', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={3} />);

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
});
it('shows inline error for invalid email field', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears validation error when email is corrected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears role validation error when role is selected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers

View File

@@ -34,7 +34,7 @@ describe('InvalidQueryState', () => {
});
it('runs the callback, then opens support', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onContactSupport = jest.fn();
render(
<InvalidQueryState

View File

@@ -1,5 +1,5 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent, within } from 'tests/test-utils';
import { render, screen, userEvent } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import SearchBar from '../SearchBar';
@@ -40,7 +40,9 @@ function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
}
function searchContent(): HTMLElement {
return within(screen.getByTestId('list-search')).getByRole('textbox');
return screen
.getByTestId('list-search')
.querySelector('.cm-content') as HTMLElement;
}
describe('SearchBar — run on blur', () => {

View File

@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
});
it('selects a view by id', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const props = renderRail();
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));

View File

@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log link from the ⋯ menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log from the ⋯ menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const logs = [makeLog('log-0'), makeLog('log-1')];
const onNavigateLog = jest.fn();

View File

@@ -1,39 +1,46 @@
import { render, screen, within } from 'tests/test-utils';
import { render } from '@testing-library/react';
import { FontSize } from 'container/OptionsMenu/types';
import LogStateIndicator from './LogStateIndicator';
describe('LogStateIndicator', () => {
it('renders correctly with default props', () => {
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 { container } = render(
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
);
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 { rerender } = render(
const { container: containerInfo } = render(
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-info-0',
);
expect(
containerInfo.querySelector('.line')?.classList.contains('severity-info-0'),
).toBe(true);
rerender(
const { container: containerWarning } = render(
<LogStateIndicator severityText="WARNING" fontSize={FontSize.MEDIUM} />,
);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-warn-0',
);
expect(
containerWarning
.querySelector('.line')
?.classList.contains('severity-warn-0'),
).toBe(true);
rerender(
const { container: containerError } = render(
<LogStateIndicator severityText="ERROR" fontSize={FontSize.MEDIUM} />,
);
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
'severity-error-0',
);
expect(
containerError
.querySelector('.line')
?.classList.contains('severity-error-0'),
).toBe(true);
});
});

View File

@@ -138,11 +138,8 @@ function LogStateIndicator({
const severityClass = getSeverityClass(severityText, severityNumber);
return (
<div className="log-state-indicator" data-testid="log-state-indicator">
<div
className={cx('line', fontSize, severityClass)}
data-testid="log-state-indicator-line"
/>
<div className="log-state-indicator">
<div className={cx('line', fontSize, severityClass)} />
</div>
);
}

View File

@@ -128,9 +128,7 @@ function OptionsMenu({
>
<span className="menu-row">
{size}
{fontSizeValue === size && (
<Check size={14} data-testid="font-size-option-check" />
)}
{fontSizeValue === size && <Check size={14} />}
</span>
</Button>
))}
@@ -158,7 +156,7 @@ function OptionsMenu({
</Button>
</div>
<div className="horizontal-line" />
<div className="menu-container" data-testid="format-options-menu">
<div className="menu-container">
<div className="title">FORMAT</div>
<div className="menu-items">
@@ -172,9 +170,7 @@ function OptionsMenu({
<div className={cx('item-label')}>
{item.label}
{selectedItem === item.key && (
<Check size={12} data-testid="format-check-icon" />
)}
{selectedItem === item.key && <Check size={12} />}
</div>
</div>
))}

View File

@@ -5,7 +5,6 @@ import {
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
@@ -35,14 +34,13 @@ describe('LogsFormatOptionsMenu (unit)', () => {
mockUpdateFormatting.mockClear();
});
async function setup(): Promise<{
user: ReturnType<typeof userEvent.setup>;
function 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' },
@@ -78,11 +76,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
// Open the popover menu by default for each test
const formatButton = getByTestId('periscope-btn-format-options');
await user.click(formatButton);
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));
return {
user,
getByTestId,
findItemByLabel,
formatOnChange,
maxLinesOnChange,
fontSizeOnChange,
@@ -91,36 +94,31 @@ describe('LogsFormatOptionsMenu (unit)', () => {
// Covers: opens menu, changes format selection, updates max-lines, changes font size
it('opens and toggles format selection', async () => {
const { user, formatOnChange } = await setup();
const { findItemByLabel, formatOnChange } = setup();
// Assert initial selection
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
expect(
within(screen.getByTestId('format-option-table')).getByTestId(
'format-check-icon',
),
).toBeInTheDocument();
const columnItem = findItemByLabel('Column') as Element;
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
expect(columnItem.querySelector('svg')).toBeInTheDocument();
// Change selection to 'Raw'
await user.click(screen.getByTestId('format-option-raw'));
const rawItem = findItemByLabel('Raw') as Element;
fireEvent.click(rawItem as HTMLElement);
await waitFor(() => {
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
expect(
within(screen.getByTestId('format-option-raw')).getByTestId(
'format-check-icon',
),
).toBeInTheDocument();
const rawEl = findItemByLabel('Raw') as Element;
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
expect(rawEl.querySelector('svg')).toBeInTheDocument();
});
expect(formatOnChange).toHaveBeenCalledWith('raw');
});
it('increments max-lines and calls onChange', async () => {
const { user, maxLinesOnChange, getByTestId } = await setup();
const { maxLinesOnChange, getByTestId } = setup();
// Increment max lines
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
const initial = Number(input.value);
await user.click(screen.getByRole('button', { name: 'More lines per row' }));
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
await waitFor(() => {
expect(Number(input.value)).toBe(initial + 1);
@@ -131,8 +129,9 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('clamps a typed max-lines value to 10', async () => {
const { user, maxLinesOnChange, getByTestId } = await setup();
const { maxLinesOnChange, getByTestId } = setup();
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
const user = userEvent.setup();
await user.clear(input);
await user.type(input, '15');
@@ -143,9 +142,10 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('stops max-lines at 10', async () => {
const { user, getByTestId } = await setup();
const { getByTestId } = 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,23 +155,19 @@ describe('LogsFormatOptionsMenu (unit)', () => {
});
it('changes font size to MEDIUM and calls onChange', async () => {
const { user, fontSizeOnChange, getByTestId } = await setup();
const { fontSizeOnChange, getByTestId } = setup();
// Open font dropdown
await user.click(getByTestId('font-size-select'));
fireEvent.click(getByTestId('font-size-select'));
// Choose MEDIUM
await user.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
await waitFor(() => {
expect(
within(getByTestId(`font-size-option-${FontSize.MEDIUM}`)).getByTestId(
'font-size-option-check',
),
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
).toBeInTheDocument();
expect(
within(getByTestId(`font-size-option-${FontSize.SMALL}`)).queryByTestId(
'font-size-option-check',
),
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
).not.toBeInTheDocument();
});
await waitFor(() => {
@@ -216,16 +212,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
renderWithOnOpen(undefined, 'table');
expect(
screen.queryByTestId('periscope-btn-edit-columns'),
).not.toBeInTheDocument();
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
).toBeNull();
});
it('does not render "Edit columns" row when format is not table', () => {
renderWithOnOpen(jest.fn(), 'raw');
expect(
screen.queryByTestId('periscope-btn-edit-columns'),
).not.toBeInTheDocument();
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
).toBeNull();
});
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
@@ -237,7 +233,7 @@ describe('LogsFormatOptionsMenu (unit)', () => {
expect(onOpenColumns).toHaveBeenCalledTimes(1);
await waitFor(() => {
// Popover content unmounts on close.
expect(screen.queryByTestId('format-option-table')).not.toBeInTheDocument();
expect(document.querySelector('.menu-container')).toBeNull();
});
});
});

View File

@@ -74,7 +74,8 @@ function Harness({
}
const getView = (): EditorView => {
const view = EditorView.findFromDOM(screen.getByTestId('markdown-editor'));
const dom = document.querySelector('.cm-editor');
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
if (!view) {
throw new Error('editor view not mounted');
}
@@ -150,9 +151,11 @@ describe('MarkdownEditor', () => {
render(<Harness initialValue={'## Runbook\nowner {{team}}'} />);
await waitFor(() => {
expect(screen.getByText('## Runbook')).toHaveClass('cm-md-heading');
expect(document.querySelector('.cm-md-heading')).toBeInTheDocument();
});
expect(screen.getByText('{{team}}')).toHaveClass('cm-md-variable');
expect(document.querySelector('.cm-md-variable')).toHaveTextContent(
'{{team}}',
);
});
describe('uncontrolled document', () => {

View File

@@ -189,13 +189,7 @@ function MembersTable({
<span className="members-pagination-range">
{range[0]} &#8212; {range[1]}
</span>
<span
className="members-pagination-total"
data-testid="members-pagination-total"
>
{' '}
of {_total}
</span>
<span className="members-pagination-total"> of {_total}</span>
</>
);

View File

@@ -68,7 +68,7 @@ describe('MembersTable', () => {
const onRowClick = jest.fn() as jest.MockedFunction<
(member: MemberRow) => void
>;
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const deletedMember: MemberRow = {
id: 'user-del',
name: 'Dave Deleted',
@@ -129,7 +129,7 @@ describe('MembersTable', () => {
});
it('hides pagination when total does not exceed pageSize', () => {
render(
const { container } = render(
<MembersTable
{...defaultProps}
data={mockActiveMembers}
@@ -139,12 +139,12 @@ describe('MembersTable', () => {
);
expect(
screen.queryByTestId('members-pagination-total'),
container.querySelector('.members-table-pagination'),
).not.toBeInTheDocument();
});
it('shows pagination when total exceeds pageSize', () => {
render(
const { container } = render(
<MembersTable
{...defaultProps}
data={mockActiveMembers}
@@ -153,8 +153,11 @@ describe('MembersTable', () => {
/>,
);
expect(screen.getByTestId('members-pagination-total')).toHaveTextContent(
'of 25',
);
expect(
container.querySelector('.members-table-pagination'),
).toBeInTheDocument();
expect(
container.querySelector('.members-pagination-total'),
).toBeInTheDocument();
});
});

View File

@@ -1,4 +1,4 @@
import { render, screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
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 { asFragment } = render(
const { container } = render(
<MessageTip
show
message="Success Tips"
action={<button type="button">Close</button>}
/>,
);
expect(asFragment()).toMatchSnapshot();
expect(container.firstChild).toMatchSnapshot();
});
});

View File

@@ -1,8 +1,7 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`MessageTip custom action 1`] = `
<DocumentFragment>
.c0 {
.c0 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
@@ -10,47 +9,46 @@ 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"
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"
>
<span
aria-label="info-circle"
class="anticon anticon-info-circle ant-alert-icon"
role="img"
<svg
aria-hidden="true"
data-icon="info-circle"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<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>
<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"
>
<div
class="ant-alert-content"
class="ant-alert-description"
>
<div
class="ant-alert-description"
>
Success Tips
</div>
</div>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
Success Tips
</div>
</div>
</DocumentFragment>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
</div>
</div>
`;

View File

@@ -632,11 +632,7 @@ 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"
data-testid="highlight-text"
>
<span key={uniqueKey} className="highlight-text">
{part}
</span>
) : (
@@ -750,7 +746,6 @@ 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();
@@ -782,9 +777,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
{highlightMatchedText(String(option.label || ''), searchText)}
</span>
{(option.type === 'custom' || option.type === 'regex') && (
<div className="option-badge" data-testid="option-badge">
{capitalize(option.type)}
</div>
<div className="option-badge">{capitalize(option.type)}</div>
)}
{option.value && ensureValidOption(option.value) && (
<Button
@@ -1569,7 +1562,6 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
<div
ref={dropdownRef}
className="custom-multiselect-dropdown"
data-testid="custom-multiselect-dropdown"
onMouseDown={handleDropdownMouseDown}
onClick={handleDropdownClick}
onKeyDown={handleKeyDown}
@@ -1591,7 +1583,6 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
active: activeIndex === 0,
})}
key={`all-option-${allOptionsSelected}`}
data-testid="all-option"
id="option-0"
onMouseEnter={(): void => {
setActiveIndex(0);
@@ -1650,7 +1641,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
</div>
</div>
<div className="divider" data-testid="all-option-divider" />
<div className="divider" />
</>
)}
@@ -1720,11 +1711,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
)}
{/* Navigation help footer */}
<div
className="navigation-footer"
role="note"
data-testid="navigation-footer"
>
<div className="navigation-footer" role="note">
{!loading &&
!errorMessage &&
!noDataMessage &&
@@ -1739,7 +1726,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</section>
)}
{loading && (
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -1747,7 +1734,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
)}
{!loading && waitingMessage && (
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -1757,7 +1744,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
</div>
)}
{errorMessage && !loading && !waitingMessage && (
<div className="navigation-error" data-testid="navigation-error">
<div className="navigation-error">
<div className="navigation-text">
{errorMessage || SOMETHING_WENT_WRONG}
</div>
@@ -1972,7 +1959,6 @@ 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
? {

View File

@@ -170,11 +170,7 @@ 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"
data-testid="highlight-text"
>
<span key={uniqueKey} className="highlight-text">
{part}
</span>
) : (
@@ -224,7 +220,6 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
selected: isSelected,
active: isActive,
})}
data-testid={`option-item-${option.value}`}
onClick={(e): void => {
e.stopPropagation();
handleSelection();
@@ -246,9 +241,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
{highlightMatchedText(String(option.label || ''), searchText)}
</span>
{option.type === 'custom' && (
<div className="option-badge" data-testid="option-badge">
{capitalize(option.type)}
</div>
<div className="option-badge">{capitalize(option.type)}</div>
)}
</div>
</div>
@@ -275,7 +268,6 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
() => (
<X
size="md"
data-testid="custom-select-clear"
onClick={(e): void => {
e.stopPropagation();
if (onChange) {
@@ -536,7 +528,6 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
<div
ref={dropdownRef}
className="custom-select-dropdown"
data-testid="custom-select-dropdown"
onClick={handleDropdownClick}
onKeyDown={handleKeyDown}
onScroll={handleDropdownScroll}
@@ -596,7 +587,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</section>
)}
{loading && (
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -604,7 +595,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</div>
)}
{!loading && waitingMessage && (
<div className="navigation-loading" data-testid="navigation-loading">
<div className="navigation-loading">
<div className="navigation-icons">
<Loader size="md" className="animate-spin" />
</div>
@@ -614,7 +605,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
</div>
)}
{errorMessage && !loading && (
<div className="navigation-error" data-testid="navigation-error">
<div className="navigation-error">
<div className="navigation-text">
{errorMessage || SOMETHING_WENT_WRONG}
</div>

View File

@@ -1,9 +1,8 @@
import { useState } from 'react';
import { VirtuosoMockContext } from 'react-virtuoso';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomMultiSelect from '../CustomMultiSelect';
import type { CustomMultiSelectProps } from '../types';
// Mock scrollIntoView which isn't available in JSDOM
window.HTMLElement.prototype.scrollIntoView = jest.fn();
@@ -50,26 +49,6 @@ 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;
@@ -135,8 +114,16 @@ 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
await user.type(combobox, 'fro');
if (searchInput) {
await user.type(searchInput, 'fro');
}
// Verify the component renders without crashing
expect(combobox).toBeInTheDocument();
@@ -154,20 +141,30 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'frontend');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'frontend');
}
// Should show the Frontend option in dropdown for exact match
await waitFor(() => {
// Check for highlighted "frontend" text
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('Frontend');
// Frontend option should be visible in dropdown - use a simpler approach
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
const optionLabels = document.querySelectorAll('.option-label-text');
const hasFrontendOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('Frontend'),
);
expect(hasFrontendOption).toBe(true);
});
// Press Enter to select the exact match
@@ -191,31 +188,49 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'end');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
// Should filter to show only Frontend and Backend with highlighted "end"
await waitFor(() => {
// Check for highlighted "end" text in the options
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('end');
// Check that Frontend and Backend options are present with highlighted text
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
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-backend')).toHaveTextContent(
'Backend',
const hasBackendOption = Array.from(optionLabels).some(
(label) =>
label.textContent?.includes('Back') && label.textContent?.includes('end'),
);
expect(hasFrontendOption).toBe(true);
expect(hasBackendOption).toBe(true);
// Other options should be filtered out
expect(
screen.queryByTestId('option-item-database'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('option-item-api-gateway'),
).not.toBeInTheDocument();
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);
});
});
@@ -231,8 +246,15 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
// Type comma-separated values
await user.type(combobox, 'test1, test2, test3');
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');
}
// Press Enter to create the comma-separated chips
await user.keyboard('{Enter}');
@@ -272,13 +294,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
expect(
screen.getByTestId('custom-multiselect-dropdown'),
).toBeInTheDocument();
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);
// Database should be at the top (after ALL option if present)
const [firstOption] = screen.getAllByTestId(/^option-item-/);
expect(firstOption).toBe(screen.getByTestId('option-item-database'));
expect(optionTexts[0]).toBe('Database');
});
});
@@ -296,20 +319,30 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
});
// Find and type in search input
await user.type(combobox, 'front');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
// Should filter to show only options containing 'front' and highlight search term
await waitFor(() => {
// Check for highlighted text within the Frontend option
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('Front');
// Should show Frontend option (highlighted) - use a simpler approach
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
const optionLabels = document.querySelectorAll('.option-label-text');
const hasFrontendOption = Array.from(optionLabels).some((label) =>
label.textContent?.includes('Frontend'),
);
expect(hasFrontendOption).toBe(true);
// Backend and Database should not be visible
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
@@ -329,13 +362,21 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'end');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
// Should highlight matching text in options
await waitFor(() => {
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('end');
});
});
@@ -352,7 +393,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'nonexistent');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'nonexistent');
}
// Should show custom value option when no matches found
await waitFor(() => {
@@ -363,11 +411,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
// Should show custom value option
const customOption = screen.getByTestId('option-item-nonexistent');
expect(customOption).toHaveTextContent('nonexistent');
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
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();
});
});
});
@@ -395,19 +445,23 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// First option should be active
await waitFor(() => {
const activeOption = screen.getByTestId('option-item-frontend');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
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 = screen.getByTestId('all-option');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption).toHaveClass('active');
expect(activeOption).toHaveAttribute('role', 'option');
expect(activeOption).toHaveTextContent('ALL');
expect(activeOption?.textContent).toContain('ALL');
});
});
@@ -445,14 +499,19 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should navigate to first option in dropdown
await waitFor(() => {
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption).toHaveClass('active');
expect(activeOption?.textContent).toBeTruthy();
});
// Tab again to move to next option
await user.tab();
await waitFor(() => {
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption?.textContent).toContain('Backend');
});
});
@@ -499,9 +558,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should have an active chip
await waitFor(() => {
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
'ant-select-selection-item-active',
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
});
// Delete the active chip
@@ -515,9 +575,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify that the active chip (backend) is highlighted for deletion
await waitFor(() => {
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
'ant-select-selection-item-active',
const activeChip = document.querySelector(
'.ant-select-selection-item-active',
);
expect(activeChip).toBeInTheDocument();
expect(activeChip).toHaveTextContent('backend');
});
});
});
@@ -626,7 +688,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
await user.click(screen.getByRole('combobox'));
const backendRow = await screen.findByTestId('option-item-backend');
const backendRow = (await screen.findByText('Backend')).closest(
'[role="option"]',
) as HTMLElement;
mockOnChange.mockClear();
await user.click(within(backendRow).getByRole('checkbox'));
@@ -662,7 +726,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
await user.click(screen.getByRole('combobox'));
const backendRow = await screen.findByTestId('option-item-backend');
const backendRow = (await screen.findByText('Backend')).closest(
'[role="option"]',
) as HTMLElement;
mockOnChange.mockClear();
await user.click(within(backendRow).getByText('Toggle'));
@@ -685,7 +751,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('Database')).toBeInTheDocument();
expect(screen.getByText('API Gateway')).toBeInTheDocument();
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
const loadingFooter = document.querySelector('.navigation-loading');
expect(loadingFooter).toBeInTheDocument();
expect(screen.getByText('Refreshing values...')).toBeInTheDocument();
});
});
@@ -703,7 +770,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
const errorFooter = document.querySelector('.navigation-error');
expect(errorFooter).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
});
@@ -745,17 +813,21 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// All chips should be selected (have selected class)
const selectedChips = screen
.getAllByTestId(/^selected-tag-/)
.filter((chip) =>
chip.classList.contains('ant-select-selection-item-selected'),
);
const selectedChips = document.querySelectorAll(
'.ant-select-selection-item-selected',
);
expect(selectedChips.length).toBeGreaterThan(0);
// Verify that all expected chips are present AND selected
const frontendChip = screen.getByTestId('selected-tag-frontend');
const backendChip = screen.getByTestId('selected-tag-backend');
const databaseChip = screen.getByTestId('selected-tag-database');
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');
expect(frontendChip).toHaveClass('ant-select-selection-item-selected');
expect(backendChip).toHaveClass('ant-select-selection-item-selected');
@@ -778,8 +850,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
/>,
);
await user.click(screen.getByLabelText('close-circle'));
expect(mockOnChange).toHaveBeenCalledWith([], []);
const clearButton = document.querySelector('.ant-select-clear');
if (clearButton) {
await user.click(clearButton as Element);
expect(mockOnChange).toHaveBeenCalledWith([], []);
}
});
it('CA-03: Individual chip removal', async () => {
@@ -792,10 +867,12 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
);
// Find and click the close button on a chip
const removeButtons = screen.getAllByLabelText(/^Remove tag /);
const removeButtons = document.querySelectorAll(
'.ant-select-selection-item-remove',
);
expect(removeButtons).toHaveLength(2);
await user.click(removeButtons[1]);
await user.click(removeButtons[1] as Element);
// Should call onChange with one item removed
expect(mockOnChange).toHaveBeenCalledWith(
@@ -834,10 +911,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// Dropdown should be hidden (not completely removed from DOM)
expect(
screen.getByTestId('custom-multiselect-dropdown'),
).toBeInTheDocument();
expect(combobox).toHaveAttribute('aria-expanded', 'false');
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(dropdown).toHaveStyle('pointer-events: none');
});
});
@@ -875,7 +951,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'custom-input');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'custom-input');
}
// Press Enter in input field
await user.keyboard('{Enter}');
@@ -901,11 +984,18 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'search-text');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'search-text');
}
// Verify search text is in input
await waitFor(() => {
expect(combobox).toHaveValue('search-text');
expect(searchInput).toHaveValue('search-text');
});
// Press Escape to close dropdown
@@ -913,8 +1003,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Dropdown should close and search text should be cleared
await waitFor(() => {
expect(combobox).toHaveAttribute('aria-expanded', 'false');
expect(combobox).toHaveValue('');
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
expect(searchInput).toHaveValue('');
});
});
});
@@ -938,7 +1029,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(allOption).toBeInTheDocument();
// Check for divider after ALL option
expect(screen.getByTestId('all-option-divider')).toBeInTheDocument();
const divider = document.querySelector('.divider');
expect(divider).toBeInTheDocument();
});
});
@@ -994,7 +1086,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await waitFor(() => {
// Should show navigation footer
expect(screen.getByTestId('navigation-footer')).toBeInTheDocument();
const footer = document.querySelector('.navigation-footer');
expect(footer).toBeInTheDocument();
// Should show navigation hint
expect(screen.getByText('to navigate')).toBeInTheDocument();
@@ -1068,9 +1161,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
describe('Advanced Keyboard Navigation (AKN)', () => {
it('AKN-01: Shift + Arrow + Del chip deletion', async () => {
renderWithVirtuoso(
<StatefulMultiSelect
initialValue={['frontend', 'backend', 'database']}
<CustomMultiSelect
options={mockOptions}
onChange={mockOnChange}
value={['frontend', 'backend', 'database']}
/>,
);
@@ -1082,10 +1176,12 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Should have an active chip - verify initial chip
await waitFor(() => {
// Verify we're on the last chip (database)
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
'ant-select-selection-item-active',
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');
});
// Use Shift + Arrow to navigate to previous chip
@@ -1093,10 +1189,12 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify we're on a different chip (backend)
await waitFor(() => {
// Verify we moved to the previous chip (backend)
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
'ant-select-selection-item-active',
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');
});
// Use Del to delete the active chip
@@ -1105,9 +1203,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
// Verify the chip was deleted
await waitFor(() => {
// Check that the backend chip is no longer present
expect(
screen.queryByTestId('selected-tag-backend'),
).not.toBeInTheDocument();
const backendChip = document.querySelector('.ant-select-selection-item');
expect(backendChip?.textContent).not.toContain('backend');
// Verify onChange was called with the updated value (without backend)
expect(mockOnChange).toHaveBeenCalledWith(
@@ -1138,8 +1235,9 @@ 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(combobox).toHaveAttribute('aria-expanded', 'false');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
});
});
});
@@ -1158,20 +1256,32 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('ALL')).toBeInTheDocument();
});
await user.type(combobox, 'front');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
// Should show highlighted options with correct order
await waitFor(() => {
// Check for highlighted text
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('front');
// Get all option items to check the order
const optionTexts = screen
.getAllByTestId(/^option-item-/)
.map((item) => item.textContent?.trim());
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);
// Custom value "front" should appear first (above Frontend)
// The text should contain "front"
@@ -1215,7 +1325,12 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
});
// Now type something and press Enter to save
await user.type(combobox, 'custom-value');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'custom-value');
}
// Press Enter to save (should create custom value)
await user.keyboard('{Enter}');
@@ -1249,8 +1364,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(screen.getByLabelText('close-circle'));
await user.click(clearButton as Element);
// Should call onChange immediately (no loading state in this component)
expect(mockOnChangeWithDelay).toHaveBeenCalledWith([], []);
@@ -1308,13 +1426,19 @@ 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
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
await user.type(combobox, longSearchValue);
if (searchInput) {
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
await user.type(searchInput, 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',
);
@@ -1345,16 +1469,25 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
// Test regex pattern
await user.type(combobox, '.*test.*');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
// Test regex pattern
await user.type(searchInput, '.*test.*');
}
// Should create custom value for regex pattern
await waitFor(() => {
const regexOption = screen.getByTestId('option-item-.*test.*');
expect(regexOption).toHaveTextContent('.*test.*');
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
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();
});
// Press Enter to create the regex value
@@ -1437,7 +1570,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
await user.keyboard('{Escape}');
await waitFor(() => {
expect(combobox).toHaveAttribute('aria-expanded', 'false');
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
});
});
});

View File

@@ -4,9 +4,8 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
} from '@testing-library/react';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -30,6 +29,9 @@ 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();
@@ -59,7 +61,8 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Check that retry button (ReloadOutlined icon) is present
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
});
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
@@ -85,11 +88,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).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)';
@@ -105,7 +108,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
// Open dropdown
const selectElement = screen.getByRole('combobox');
await user.click(selectElement);
fireEvent.mouseDown(selectElement);
// Wait for dropdown to appear
await waitFor(() => {
@@ -113,7 +116,10 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Find and click the retry button
await user.click(screen.getByTestId('retry-button'));
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
fireEvent.click(retryButton as Element);
// Verify onRetry was called
expect(mockOnRetry).toHaveBeenCalledTimes(1);

View File

@@ -4,10 +4,9 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -157,7 +156,6 @@ describe('CustomMultiSelect Component', () => {
});
it('removes a tag when clicked', async () => {
const user = userEvent.setup();
const handleChange = jest.fn();
renderWithVirtuoso(
<CustomMultiSelect
@@ -168,7 +166,10 @@ describe('CustomMultiSelect Component', () => {
);
// Find close button on Option 1 tag and click it
await user.click(screen.getByLabelText('Remove tag option1'));
const closeButtons = document.querySelectorAll(
'.ant-select-selection-item-remove',
);
fireEvent.click(closeButtons[0]);
// Verify onChange was called with remaining option
expect(handleChange).toHaveBeenCalledWith(
@@ -178,24 +179,39 @@ describe('CustomMultiSelect Component', () => {
});
it('filters options when searching', async () => {
const user = userEvent.setup();
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
// Open dropdown
const selectElement = screen.getByRole('combobox');
await user.click(selectElement);
fireEvent.mouseDown(selectElement);
// Type into search box - the combobox is the search input
await user.type(selectElement, '2');
// Type into search box - get input directly
const inputElement = selectElement.querySelector('input');
if (inputElement) {
fireEvent.change(inputElement, { target: { value: '2' } });
}
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']);
// 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);
});
});
it('renders grouped options correctly', async () => {

View File

@@ -1,4 +1,5 @@
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomSelect from '../CustomSelect';
@@ -66,19 +67,34 @@ 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
await user.type(combobox, 'fro');
if (searchInput) {
await user.type(searchInput, 'fro');
}
// Check that custom value appears in dropdown with custom tag
await waitFor(() => {
// Find the custom option with "fro" text and "Custom" badge
const customOption = screen.getByTestId('option-item-fro');
expect(customOption).toHaveTextContent('fro');
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();
// Verify it has the custom badge
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
const optionItem = customOption?.closest('.option-item');
const badge = optionItem?.querySelector('.option-badge');
expect(badge).toBeInTheDocument();
expect(badge?.textContent).toBe('Custom');
});
// Press Enter to create the custom value
@@ -104,20 +120,30 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
await user.type(combobox, 'frontend');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'frontend');
}
// Should show the Frontend option in dropdown for exact match
await waitFor(() => {
// Check for highlighted "frontend" text
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('Frontend');
// Frontend option should be visible in dropdown - use a simpler approach
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
const optionContents = document.querySelectorAll('.option-content');
const hasFrontendOption = Array.from(optionContents).some((content) =>
content.textContent?.includes('Frontend'),
);
expect(hasFrontendOption).toBe(true);
});
// Press Enter to select the exact match
@@ -148,11 +174,14 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
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);
// Database should be at the top
const [firstOption] = screen.getAllByTestId(/^option-item-/);
expect(firstOption).toHaveTextContent('Database');
expect(optionTexts[0]).toContain('Database');
});
});
@@ -168,20 +197,30 @@ describe('CustomSelect - Comprehensive Tests', () => {
});
// Find and type in search input
await user.type(combobox, 'front');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
// Should filter to show only options containing 'front'
await waitFor(() => {
// Check for highlighted text within the Frontend option
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('Front');
// Should show Frontend option (highlighted) - use a simpler approach
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
'Frontend',
const optionContents = document.querySelectorAll('.option-content');
const hasFrontendOption = Array.from(optionContents).some((content) =>
content.textContent?.includes('Frontend'),
);
expect(hasFrontendOption).toBe(true);
// Backend and Database should not be visible
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
@@ -199,13 +238,21 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
await user.type(combobox, 'end');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'end');
}
// Should highlight matching text in options
await waitFor(() => {
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('end');
});
});
@@ -220,7 +267,14 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
await user.type(combobox, 'nonexistent');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'nonexistent');
}
// Should show custom value option when no matches found
await waitFor(() => {
@@ -231,11 +285,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
// Should show custom value option
const customOption = screen.getByTestId('option-item-nonexistent');
expect(customOption).toHaveTextContent('nonexistent');
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
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();
});
});
});
@@ -257,15 +313,19 @@ 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(screen.getByTestId('option-item-backend')).toHaveClass('active');
expect(activeOption?.textContent).toContain('Backend');
});
// Arrow up should go to previous option
await user.keyboard('{ArrowUp}');
await waitFor(() => {
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
expect(activeOption?.textContent).toContain('Frontend');
});
});
@@ -350,7 +410,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.keyboard('{Tab}');
// Should still be within dropdown context
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
const dropdown = document.querySelector('.custom-select-dropdown');
expect(dropdown).toBeInTheDocument();
});
});
@@ -392,7 +453,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
const loadingFooter = document.querySelector('.navigation-loading');
expect(loadingFooter).toBeInTheDocument();
});
});
@@ -409,7 +471,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
await user.click(combobox);
await waitFor(() => {
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
const errorFooter = document.querySelector('.navigation-error');
expect(errorFooter).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
});
@@ -542,7 +605,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(combobox).toHaveFocus();
await waitFor(() => {
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
const dropdown = document.querySelector('.custom-select-dropdown');
expect(dropdown).toBeInTheDocument();
});
// Focus should remain manageable
@@ -615,7 +679,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Dropdown should close
await waitFor(() => {
expect(combobox).toHaveAttribute('aria-expanded', 'false');
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
});
});
@@ -649,7 +714,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Should navigate to first option in dropdown
await waitFor(() => {
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
const activeOption = document.querySelector('.option-item.active');
expect(activeOption).toBeInTheDocument();
});
});
});
@@ -666,20 +732,32 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
await user.type(combobox, 'front');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
await user.type(searchInput, 'front');
}
// Should show highlighted options with correct order
await waitFor(() => {
// Check for highlighted text
const highlightTexts = screen
.getAllByTestId('highlight-text')
.map((el) => el.textContent);
const highlightedElements = document.querySelectorAll('.highlight-text');
const highlightTexts = Array.from(highlightedElements).map(
(el) => el.textContent,
);
expect(highlightTexts).toContain('front');
// Get all option items to check the order
const optionTexts = screen
.getAllByTestId(/^option-item-/)
.map((item) => item.textContent?.trim());
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);
// Custom value "front" should appear first (above Frontend)
// The text includes "Custom" badge, so check for "front" in the text
@@ -729,7 +807,12 @@ describe('CustomSelect - Comprehensive Tests', () => {
});
// Now type something and press Enter to save
await user.type(combobox, 'custom-value');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'custom-value');
}
// Press Enter to save (should close dropdown)
await user.keyboard('{Enter}');
@@ -764,8 +847,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(screen.getByTestId('custom-select-clear'));
await user.click(clearButton as Element);
// Should call onChange immediately (no loading state in this component)
expect(mockOnChangeWithDelay).toHaveBeenCalledWith(undefined, undefined);
@@ -784,8 +870,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
/>,
);
const clearButton = document.querySelector('.ant-select-clear');
expect(clearButton).toBeInTheDocument();
// Click clear button
await user.click(screen.getByTestId('custom-select-clear'));
await user.click(clearButton as Element);
// Should clear the single selection
expect(mockOnChange).toHaveBeenCalledWith(undefined, undefined);
@@ -838,13 +927,19 @@ 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
const longSearchValue = 'a'.repeat(100);
await user.type(combobox, longSearchValue);
if (searchInput) {
const longSearchValue = 'a'.repeat(100);
await user.type(searchInput, 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',
);
@@ -867,7 +962,12 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(combobox).toHaveFocus();
// Should be able to type even with loading state
await user.type(combobox, 'test');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
if (searchInput) {
await user.type(searchInput, 'test');
}
// Should not be blocked by loading spinner
expect(combobox).not.toBeDisabled();
@@ -886,16 +986,25 @@ describe('CustomSelect - Comprehensive Tests', () => {
expect(screen.getByText('Frontend')).toBeInTheDocument();
});
// Test regex pattern
await user.type(combobox, '.*test.*');
const searchInput = document.querySelector(
'.ant-select-selection-search-input',
);
expect(searchInput).toBeInTheDocument();
if (searchInput) {
// Test regex pattern
await user.type(searchInput, '.*test.*');
}
// Should create custom value for regex pattern
await waitFor(() => {
const regexOption = screen.getByTestId('option-item-.*test.*');
expect(regexOption).toHaveTextContent('.*test.*');
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
'Custom',
);
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();
});
// Press Enter to create the regex value
@@ -967,7 +1076,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
// Dropdown should close after selection in single select
await waitFor(() => {
expect(combobox).toHaveAttribute('aria-expanded', 'false');
const dropdown = document.querySelector('.ant-select-dropdown');
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
});
});
});

View File

@@ -1,11 +1,5 @@
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomSelect from '../CustomSelect';
@@ -99,12 +93,11 @@ describe('CustomSelect Component', () => {
// Dropdown should only show Option 2
await waitFor(() => {
// Check that the dropdown is present
const dropdownElement = screen.getByTestId('custom-select-dropdown');
const dropdownElement = document.querySelector('.custom-select-dropdown');
expect(dropdownElement).toBeInTheDocument();
// Use a simple approach to verify filtering
const allOptionsInDropdown =
within(dropdownElement).queryAllByTestId(/^option-item-/);
const allOptionsInDropdown = document.querySelectorAll('.option-item');
let foundOption2 = false;
allOptionsInDropdown.forEach((option) => {

View File

@@ -40,7 +40,7 @@ function ListViewOrderBy({
const [searchInput, setSearchInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const [selectOptions, setSelectOptions] = useState<
{ label: string; value: string; 'data-testid': string }[]
{ label: string; value: string }[]
>([]);
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -75,16 +75,8 @@ function ListViewOrderBy({
setSelectOptions(
uniqueKeys.flatMap((key) => [
{
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',
},
{ label: `${key} (desc)`, value: `${key}:desc` },
{ label: `${key} (asc)`, value: `${key}:asc` },
]),
);
}, [data, searchInput, extraKeysSignature]);

View File

@@ -59,9 +59,9 @@ const openDropdown = (): void => {
};
const getOptionLabels = (): string[] =>
screen
.queryAllByTestId('list-view-order-by-option')
.map((node) => node.textContent ?? '');
Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(
(node) => node.textContent ?? '',
);
describe('ListViewOrderBy', () => {
beforeEach(() => {

View File

@@ -1,7 +1,8 @@
import { act, render, screen, userEvent, within } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, 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 {
@@ -21,17 +22,21 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
});
}
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
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);
}
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);
});
// 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)
);
}
describe('OverflowInputToolTip', () => {
@@ -39,10 +44,6 @@ 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
@@ -50,9 +51,16 @@ describe('OverflowInputToolTip', () => {
await userEvent.hover(screen.getByRole('textbox'));
const tooltip = await screen.findByRole('tooltip');
await waitFor(() => {
expect(queryTooltipInner()).not.toBeNull();
});
const tooltipInner = queryTooltipInner();
if (!tooltipInner) {
throw new Error('Tooltip inner not found');
}
expect(
within(tooltip).getByText('Very long overflowing text'),
within(tooltipInner).getByText('Very long overflowing text'),
).toBeInTheDocument();
});
@@ -61,9 +69,11 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Short text" />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
@@ -71,9 +81,11 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Long but input not clamped" />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('uncontrolled input allows typing', async () => {
@@ -90,20 +102,24 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Overflowing!" disabled />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
render(<OverflowInputToolTip value="Snapshot" />);
const mirror = screen.getByTestId('overflow-input-mirror');
const input = screen.getByRole('textbox');
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
const mirror = container.querySelector('.overflow-input-mirror');
const input = container.querySelector('input') as HTMLInputElement | null;
expect(mirror.textContent).toBe('Snapshot');
expect(input).toHaveValue('Snapshot');
expect(mirror).toBeTruthy();
expect(mirror?.textContent).toBe('Snapshot');
expect(input).toBeTruthy();
expect(input?.value).toBe('Snapshot');
// width should be set inline (component calculates width on mount)
expect(input.getAttribute('style')).toContain('width:');
expect(input?.getAttribute('style')).toContain('width:');
});
});

View File

@@ -49,12 +49,7 @@ function OverflowInputToolTip({
return (
<>
<span
ref={mirrorRef}
aria-hidden
className="overflow-input-mirror"
data-testid="overflow-input-mirror"
/>
<span ref={mirrorRef} aria-hidden className="overflow-input-mirror" />
<Tooltip title={tooltipTitle} placement={tooltipPlacement}>
<Input
{...rest}

View File

@@ -317,20 +317,23 @@ function QuerySearch({
500,
);
const toggleSuggestions = useCallback((timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (editorRef.current.hasFocus) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
const toggleSuggestions = useCallback(
(timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (isFocused) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
return (): void => clearTimeout(timeoutId);
}, []);
return (): void => clearTimeout(timeoutId);
},
[isFocused],
);
const fetchKeySuggestions = useCallback(
async (searchText?: string): Promise<void> => {
@@ -1594,10 +1597,7 @@ function QuerySearch({
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
{isScopedFilter && !showScopeChip ? (
<Tooltip title={initialExpression || ''} placement="left">
<div
className="query-search-initial-scope-label"
data-testid="query-search-initial-scope-label"
>
<div className="query-search-initial-scope-label">
<Filter
size={14}
style={{

View File

@@ -168,7 +168,6 @@ 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 = '×';

View File

@@ -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, within } from 'tests/test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import type {
IBuilderQuery,
Query,
@@ -19,7 +19,6 @@ 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.
@@ -117,7 +116,7 @@ async function enterAggregation(
queryData: IBuilderQuery = aiQuery,
currentQuery?: Query,
): Promise<void> {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2Provider>
<QueryAggregationSelect queryData={queryData} />
@@ -126,9 +125,12 @@ async function enterAggregation(
{ queryBuilderOverrides: currentQuery && { currentQuery } },
);
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
'textbox',
);
const content = (
await screen.findByTestId(EDITOR_TEST_ID)
).querySelector<HTMLElement>('.cm-content');
if (!content) {
throw new Error('CodeMirror content element not rendered');
}
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);
@@ -136,10 +138,10 @@ async function enterAggregation(
}
function suggestionLabels(): string[] {
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((option) => option.textContent ?? '')
.sort();
return Array.from(
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
(label) => label.textContent ?? '',
).sort();
}
describe('QueryAggregationSelect field suggestions for an AI query', () => {
@@ -159,10 +161,9 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
async ({ aggregation, fieldDataType, labels }) => {
await enterAggregation(aggregation);
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual(labels);
expect(keysRequests).toHaveLength(0);
expect(
aiKeysRequests.map((params) => ({
@@ -184,13 +185,14 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
);
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]);
await waitFor(
() =>
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]),
{ timeout: SUGGESTIONS_TIMEOUT_MS },
);
expect(keysRequests).toHaveLength(0);
},
TEST_TIMEOUT_MS,

View File

@@ -1,14 +1,13 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { render, userEvent, waitFor } 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 EDITOR_TEST_ID = 'query-where-clause-editor';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
beforeAll(() => {
mockCodeMirrorDomApis();
@@ -111,7 +110,11 @@ async function renderAndType(text: string): Promise<HTMLElement> {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => {
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, text);
return editor;
@@ -125,26 +128,32 @@ async function typeKeyThenEnterOperatorContext(
): Promise<void> {
const editor = await renderAndType(key);
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
await waitFor(() => {
expect(visibleOptionLabels()).toContain(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 findCompletionOption(EDITOR_TEST_ID, '=');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('=');
});
}
function visibleOptionLabels(): string[] {
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((el) => el.textContent ?? '');
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).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 findCompletionOption(EDITOR_TEST_ID, 'status.code');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('status.code');
});
const statusOptions = visibleOptionLabels().filter(
(label) => label === 'status.code',
@@ -155,7 +164,9 @@ describe('QuerySearch context-prefixed key suggestions', () => {
it('shows context-scoped suggestions for a complete context prefix', async () => {
await renderAndType('attribute.');
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('attribute.status.code');
});
const labels = visibleOptionLabels();
// Literal key name match ranks first

View File

@@ -2,9 +2,7 @@ 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,
@@ -16,9 +14,8 @@ import { DataSource } from 'types/common/queryBuilder';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const EDITOR_TEST_ID = 'query-where-clause-editor';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
// Mock DOM APIs that CodeMirror needs
beforeAll(() => {
@@ -78,7 +75,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// CodeMirror renders a contenteditable div, so we check for the container
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
const editorContainer = document.querySelector('.query-where-clause-editor');
expect(editorContainer).toBeInTheDocument();
});
it('fetches key suggestions when typing a key (debounced)', async () => {
@@ -96,8 +94,14 @@ 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 = await findQueryEditorTextbox();
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
// Focus and type into the editor
await userEvent.click(editor);
@@ -137,7 +141,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
const editor = await findQueryEditorTextbox();
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
@@ -153,49 +162,6 @@ 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<
@@ -237,7 +203,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
const editor = await findQueryEditorTextbox();
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
@@ -284,8 +255,11 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -294,7 +268,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'";
render(
const { container } = render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -309,12 +283,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
expect(chip).toHaveTextContent('+1');
expect(chip).not.toHaveTextContent('kind_string');
expect(
screen.queryByTestId('query-search-initial-scope-label'),
container.querySelector('.query-search-initial-scope-label'),
).not.toBeInTheDocument();
});
it('keeps the scope icon unless the chip is asked for', () => {
render(
const { container } = render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -327,7 +301,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
screen.queryByTestId('query-search-scope-chip'),
).not.toBeInTheDocument();
expect(
screen.getByTestId('query-search-initial-scope-label'),
container.querySelector('.query-search-initial-scope-label'),
).toBeInTheDocument();
});
@@ -367,8 +341,11 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -394,9 +371,13 @@ 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');
@@ -431,9 +412,12 @@ 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);
},
@@ -493,9 +477,11 @@ 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 },

View File

@@ -6,22 +6,18 @@ import {
import { EditorView } from '@uiw/react-codemirror';
import { initialQueriesMap } from 'constants/queryBuilder';
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import { fireEvent, render, userEvent, waitFor } 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 EDITOR_TEST_ID = 'query-where-clause-editor';
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 FRONTEND_FILTER = "service.name = 'frontend'";
const STATUS_CODE_FILTER = "http.status_code = '500'";
@@ -72,7 +68,7 @@ function saveLogsRecent(expression: string): void {
}
function getEditorView(): EditorView | null {
const root = screen.queryByTestId(EDITOR_TEST_ID);
const root = document.querySelector<HTMLElement>(CM_ROOT_SELECTOR);
return root ? EditorView.findFromDOM(root) : null;
}
@@ -102,7 +98,14 @@ async function renderAndFocus(
): Promise<HTMLElement> {
renderLogsSearch(onChange);
const editor = await findQueryEditorTextbox();
const editor = await waitFor(
() => {
const element = document.querySelector(CM_EDITOR_SELECTOR);
expect(element).toBeInTheDocument();
return element as HTMLElement;
},
{ timeout: 2000 },
);
await userEvent.click(editor);
return editor;
@@ -232,7 +235,9 @@ describe('QuerySearch recent searches', () => {
await openRecents();
const option = await waitForPopupElement(() =>
screen.queryByText(FRONTEND_FILTER),
Array.from(
document.querySelectorAll<HTMLElement>(COMPLETION_LABEL_SELECTOR),
).find((element) => element.textContent === FRONTEND_FILTER),
);
// fireEvent: userEvent's pointerdown blurs the editor, closing the popup before CM's mousedown apply.
fireEvent.mouseDown(option);
@@ -248,9 +253,7 @@ describe('QuerySearch recent searches', () => {
await waitFor(
() => {
expect(
within(screen.getByTestId(EDITOR_TEST_ID)).queryByLabelText('Completions'),
).not.toBeInTheDocument();
expect(document.querySelector(TOOLTIP_SELECTOR)).not.toBeInTheDocument();
},
{ timeout: 2000 },
);
@@ -263,7 +266,7 @@ describe('QuerySearch recent searches', () => {
await openRecents();
const deleteButton = await waitForPopupElement(() =>
screen.queryByTestId('query-search-recent-delete'),
document.querySelector<HTMLElement>(DELETE_BUTTON_SELECTOR),
);
// fireEvent: the button preventDefaults pointerdown, which makes userEvent.click drop the mouse chain.

View File

@@ -1,14 +0,0 @@
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,
);
}

View File

@@ -1,7 +0,0 @@
import { screen, within } from 'tests/test-utils';
export async function findQueryEditorTextbox(): Promise<HTMLElement> {
return within(
await screen.findByTestId('query-where-clause-editor'),
).getByRole('textbox');
}

View File

@@ -361,7 +361,7 @@ describe('QueryAddOns', () => {
});
it('calls handleSetQueryData when reduce-to value changes', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const query = baseQuery({
reduceTo: ReduceOperators.AVG,
aggregations: [

View File

@@ -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, within } from 'tests/test-utils';
import { render, screen, userEvent } 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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
@@ -155,9 +155,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
savePreviousQuery
/>,
);
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
// render WITHOUT savePreviousQuery enabled
render(
<QueryBuilderV2
@@ -193,9 +193,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
);
// open Source and choose Meter
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
@@ -313,12 +313,19 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
await user.click(logsTrigger);
await user.click(screen.getByTitle('Traces'));
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,
);
// verify previousQuery store saved the current LOGS snapshot before switch
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
@@ -330,7 +337,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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
@@ -340,12 +347,19 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
await user.click(logsTrigger);
await user.click(screen.getByTitle('Traces'));
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,
);
// Assert that no snapshot was written
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);

View File

@@ -197,7 +197,7 @@ export default function CheckboxFilterV2(
onClear={onClear}
/>
{isOpen && isLoading && !hasLoadedOnce.current && (
<section data-testid="checkbox-filter-skeleton">
<section>
<Skeleton paragraph={{ rows: 4 }} />
</section>
)}

View File

@@ -69,7 +69,6 @@ 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 => {

View File

@@ -1,5 +1,7 @@
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { server, rest } from 'mocks-server/server';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { render } from 'tests/test-utils';
import { QuickFiltersSource } from '../../../../types';
@@ -29,9 +31,11 @@ describe('CheckboxFilterV2 - states', () => {
);
expect(screen.getByTestId('checkbox-filter-v2')).toBeInTheDocument();
await expect(
screen.findByTestId('checkbox-filter-skeleton'),
).resolves.toBeInTheDocument();
await waitFor(() => {
expect(
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
).toBeInTheDocument();
});
});
it('shows skeleton when initially closed filter is opened for the first time', async () => {
@@ -50,7 +54,7 @@ describe('CheckboxFilterV2 - states', () => {
// Filter starts closed - no skeleton, no content
expect(
screen.queryByTestId('checkbox-filter-skeleton'),
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('checkbox-filter-empty'),
@@ -61,9 +65,11 @@ describe('CheckboxFilterV2 - states', () => {
await user.click(header);
// Should show skeleton while loading, NOT "No values found"
await expect(
screen.findByTestId('checkbox-filter-skeleton'),
).resolves.toBeInTheDocument();
await waitFor(() => {
expect(
screen.getByTestId('checkbox-filter-v2').querySelector('.ant-skeleton'),
).toBeInTheDocument();
});
expect(
screen.queryByTestId('checkbox-filter-empty'),
).not.toBeInTheDocument();

View File

@@ -1,14 +1,10 @@
import type { ComponentProps } from 'react';
import { render, screen, userEvent } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BadgeConfig } from '../itemRules';
import { CheckedState } from '../../../../types';
import { CheckboxFilterV2ValueRow } from '../CheckboxFilterV2ValueRow';
type OnOnlyOrAllClick = ComponentProps<
typeof CheckboxFilterV2ValueRow
>['onOnlyOrAllClick'];
describe('CheckboxFilterV2ValueRow', () => {
const defaultProps = {
value: 'production',
@@ -115,7 +111,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('does not call onOnlyOrAllClick when disabled + clicked', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
const onOnlyOrAllClick = jest.fn();
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -131,7 +127,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('does not call onOnlyOrAllClick on keydown when disabled', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
const onOnlyOrAllClick = jest.fn();
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -185,7 +181,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('calls onOnlyOrAllClick on value text click', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
const onOnlyOrAllClick = jest.fn();
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -200,7 +196,7 @@ describe('CheckboxFilterV2ValueRow', () => {
it('calls onOnlyOrAllClick on Enter key', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
const onOnlyOrAllClick = jest.fn();
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -208,17 +204,21 @@ describe('CheckboxFilterV2ValueRow', () => {
/>,
);
const valueButton = screen
.getByText('production')
.closest('[role="button"]');
await user.tab();
await user.tab();
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
await user.keyboard('{Enter}');
if (valueButton && document.activeElement === valueButton) {
await user.keyboard('{Enter}');
}
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
expect(onOnlyOrAllClick).toHaveBeenCalled();
});
it('calls onOnlyOrAllClick on Space key', async () => {
const user = userEvent.setup();
const onOnlyOrAllClick = jest.fn() as jest.MockedFunction<OnOnlyOrAllClick>;
const onOnlyOrAllClick = jest.fn();
render(
<CheckboxFilterV2ValueRow
{...defaultProps}
@@ -226,12 +226,16 @@ describe('CheckboxFilterV2ValueRow', () => {
/>,
);
const valueButton = screen
.getByText('production')
.closest('[role="button"]');
await user.tab();
await user.tab();
expect(screen.getByTestId('checkbox-value-button-production')).toHaveFocus();
await user.keyboard(' ');
if (valueButton && document.activeElement === valueButton) {
await user.keyboard(' ');
}
expect(onOnlyOrAllClick).toHaveBeenCalledTimes(1);
expect(onOnlyOrAllClick).toHaveBeenCalled();
});
it('shows Toggle button', () => {

View File

@@ -377,7 +377,7 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
);
const filtersSkeleton = (
<div className="quick-filters-skeleton" data-testid="quick-filters-skeleton">
<div className="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} />

View File

@@ -195,9 +195,12 @@ describe('QuickFilters - AuthZ', () => {
renderWithSavedList();
await expect(
screen.findByTestId('quick-filters-skeleton'),
).resolves.toBeInTheDocument();
await waitFor(() =>
// eslint-disable-next-line testing-library/no-node-access
expect(
document.querySelector('.quick-filters-skeleton'),
).toBeInTheDocument(),
);
expect(screen.queryByText(NOT_AUTHORIZED_TEXT)).not.toBeInTheDocument();
expect(screen.queryByText(FILTER_SERVICE_NAME)).not.toBeInTheDocument();
});

View File

@@ -1,6 +1,6 @@
import { lazy } from 'react';
import { navigate } from 'lib/router/navigation';
import { fireEvent, render, screen, within } from 'tests/test-utils';
import { fireEvent, render, screen } from 'tests/test-utils';
import RouteTab from './index';
import { RouteTabProps } from './types';
@@ -69,19 +69,21 @@ describe('RouteTab component', () => {
});
it('applies the layout class alongside a custom className', () => {
render(
const { container } = render(
<RouteTab routes={testRoutes} activeKey="Tab1" className="custom-tabs" />,
);
expect(screen.getByTestId('route-tab')).toHaveClass(
expect(container.querySelector('.ant-tabs')).toHaveClass(
'routeTab',
'custom-tabs',
);
});
it('renders the active tab content inside an overlay scrollbar', () => {
render(<RouteTab routes={testRoutes} activeKey="Tab1" />);
const { container } = render(
<RouteTab routes={testRoutes} activeKey="Tab1" />,
);
expect(
within(screen.getByRole('tabpanel')).getByTestId('overlay-scrollbar'),
container.querySelector('.ant-tabs-tabpane-active > .overlay-scrollbar'),
).toHaveTextContent('Dummy Component 1');
});

View File

@@ -79,7 +79,6 @@ function RouteTab({
return (
<Tabs
className={cx(styles.routeTab, className)}
data-testid="route-tab"
onChange={onChange}
destroyInactiveTabPane
activeKey={currentRoute?.key || activeKey}

View File

@@ -192,7 +192,7 @@ function KeysTab({
if (isLoading) {
return (
<div className="keys-tab__loading" data-testid="keys-tab-loading">
<div className="keys-tab__loading">
<Skeleton active paragraph={{ rows: 4 }} />
</div>
);
@@ -257,7 +257,6 @@ function KeysTab({
role: string;
tabIndex: number;
'aria-label': string;
'data-testid': string;
} => ({
onClick: async (): Promise<void> => {
if (!isDisabled) {
@@ -275,7 +274,6 @@ function KeysTab({
role: 'button',
tabIndex: 0,
'aria-label': `Edit key ${record.name || 'options'}`,
'data-testid': `keys-tab-row-${record.id}`,
})}
/>

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
@@ -173,7 +173,7 @@ describe('AddKeyModal', () => {
});
it('keeps the footer usable when key create is denied', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(setupAuthzDenyAll());
renderModal();
@@ -208,7 +208,7 @@ describe('AddKeyModal', () => {
});
it('Cancel button closes the modal', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const cancelBtn = await screen.findByTestId('add-key-cancel-btn');

View File

@@ -106,7 +106,7 @@ describe('EditKeyModal (URL-controlled)', () => {
});
it('save calls update API, shows toast, and closes modal', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
await screen.findByDisplayValue('Original Key Name');

View File

@@ -80,13 +80,13 @@ describe('KeysTab', () => {
it('renders loading state', async () => {
renderKeysTab({ isLoading: true });
// Wait for authz to complete, then check for skeleton
await expect(
screen.findByTestId('keys-tab-loading'),
).resolves.toBeInTheDocument();
await waitFor(() => {
expect(document.querySelector('.ant-skeleton')).toBeInTheDocument();
});
});
it('renders empty state when no keys and clicking add sets add-key param', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onUrlUpdate = jest.fn();
render(
@@ -130,7 +130,12 @@ describe('KeysTab', () => {
</NuqsTestingAdapter>,
);
await user.click(await screen.findByTestId('keys-tab-row-key-1'));
const row = (await screen.findByText('Production Key')).closest('tr');
if (!row) {
throw new Error('Row not found');
}
await user.click(row);
expect(onUrlUpdate).toHaveBeenCalledWith(
expect.objectContaining({
@@ -140,7 +145,7 @@ describe('KeysTab', () => {
});
it('clicking revoke icon sets revoke-key URL param', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onUrlUpdate = jest.fn();
render(
@@ -162,7 +167,7 @@ describe('KeysTab', () => {
});
it('handles successful key revocation via RevokeKeyModal', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderKeysTab();

View File

@@ -54,7 +54,7 @@ describe('ServiceAccountsTable', () => {
const onRowClick = jest.fn() as jest.MockedFunction<
(row: ServiceAccountRow) => void
>;
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<ServiceAccountsTable

View File

@@ -61,7 +61,7 @@ export function ShiftOverlay({
}
return ReactDOM.createPortal(
<div className="shift-overlay" data-testid="shift-overlay">
<div className="shift-overlay">
<div className="shift-overlay__panel">
{navigationActions.map((action) => (
<Shortcut

View File

@@ -1,4 +1,4 @@
import { render, screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
@@ -42,15 +42,15 @@ const baseActions: CmdAction[] = [
describe('ShiftOverlay', () => {
it('renders nothing when not visible', () => {
render(
const { container } = render(
<ShiftOverlay visible={false} actions={baseActions} userRole="ADMIN" />,
);
expect(screen.queryByTestId('shift-overlay')).not.toBeInTheDocument();
expect(container.firstChild).toBeNull();
});
it('renders nothing when no navigation shortcuts exist', () => {
render(
const { container } = render(
<ShiftOverlay
visible
actions={[
@@ -65,13 +65,13 @@ describe('ShiftOverlay', () => {
/>,
);
expect(screen.queryByTestId('shift-overlay')).not.toBeInTheDocument();
expect(container.firstChild).toBeNull();
});
it('renders navigation shortcuts in a portal', () => {
render(<ShiftOverlay visible actions={baseActions} userRole="ADMIN" />);
expect(screen.getByTestId('shift-overlay')).toBeInTheDocument();
expect(document.body.querySelector('.shift-overlay')).toBeInTheDocument();
expect(screen.getByText('Traces')).toBeInTheDocument();
expect(screen.getByText('Metrics')).toBeInTheDocument();

View File

@@ -4,20 +4,18 @@ 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, testId }: TagBadgeProps): JSX.Element {
function TagBadge({ children, maxWidth }: TagBadgeProps): JSX.Element {
return (
<Badge
textTransform="none"
color="archive"
variant="outlined"
maxWidth={maxWidth}
testId={testId}
>
{children}
</Badge>

View File

@@ -67,7 +67,6 @@ function ColumnSelector<TData>({
<Checkbox
color="primary"
id={`col-${col.id}`}
testId={`${testId}-column-${col.id}`}
value={isVisible}
onChange={(): void => handleToggle(col.id, !isVisible)}
/>

View File

@@ -22,14 +22,13 @@ export function VirtuosoTableColGroup<TData>({
{visibleTanstackColumns.map((tanstackCol, index) => {
const colDef = columnDefsById.get(tanstackCol.id);
if (!colDef) {
return <col key={tanstackCol.id} data-testid="tanstack-col" />;
return <col key={tanstackCol.id} />;
}
const persistedWidth = columnSizing[tanstackCol.id];
const isLastColumn = index === fillColumnIndex;
return (
<col
key={tanstackCol.id}
data-testid="tanstack-col"
style={getColumnWidthStyle(colDef, persistedWidth, isLastColumn)}
/>
);

View File

@@ -22,7 +22,7 @@ jest.mock('../TanStackTableStateContext', () => ({
useClearRowHovered: (_rowId: string): (() => void) => mockClearRowHovered,
}));
import { fireEvent, render, screen } from 'tests/test-utils';
import { fireEvent, render, screen } from '@testing-library/react';
import TanStackCustomTableRow from '../TanStackCustomTableRow';
import type { FlatItem, TableRowContext } from '../types';
@@ -73,7 +73,7 @@ describe('TanStackCustomTableRow', () => {
...baseContext,
isRowActive: (row) => row.id === '1',
};
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -84,7 +84,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
expect(screen.getByRole('row')).toHaveClass('tableRowActive');
expect(container.querySelector('tr')).toHaveClass('tableRowActive');
});
it('does not apply active class when isRowActive returns false', () => {
@@ -92,7 +92,7 @@ describe('TanStackCustomTableRow', () => {
...baseContext,
isRowActive: (row) => row.id === 'other',
};
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -103,7 +103,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
expect(screen.getByRole('row')).not.toHaveClass('tableRowActive');
expect(container.querySelector('tr')).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,
};
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -122,12 +122,12 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
expect(screen.getByRole('row')).toHaveClass('tableRowExpansion');
expect(container.querySelector('tr')).toHaveClass('tableRowExpansion');
});
describe('hover state management', () => {
it('calls setRowHovered on mouse enter', () => {
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -138,13 +138,13 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
fireEvent.mouseEnter(row);
expect(mockSetRowHovered).toHaveBeenCalled();
});
it('calls clearRowHovered on mouse leave', () => {
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -155,7 +155,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
fireEvent.mouseLeave(row);
expect(mockClearRowHovered).toHaveBeenCalled();
});
@@ -163,7 +163,7 @@ describe('TanStackCustomTableRow', () => {
describe('virtuoso integration', () => {
it('forwards data-index attribute to tr element', () => {
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -174,12 +174,12 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
expect(row).toHaveAttribute('data-index', '0');
});
it('forwards data-item-index attribute to tr element', () => {
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -190,12 +190,12 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
expect(row).toHaveAttribute('data-item-index', '0');
});
it('forwards data-known-size attribute to tr element', () => {
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -206,7 +206,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
expect(row).toHaveAttribute('data-known-size', '40');
});
});
@@ -217,7 +217,7 @@ describe('TanStackCustomTableRow', () => {
...baseContext,
getRowStyle: () => ({ backgroundColor: 'red' }),
};
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -228,7 +228,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
expect(row).toHaveStyle({ backgroundColor: 'red' });
});
@@ -237,7 +237,7 @@ describe('TanStackCustomTableRow', () => {
...baseContext,
getRowClassName: () => 'custom-row-class',
};
render(
const { container } = render(
<table>
<tbody>
<TanStackCustomTableRow
@@ -248,7 +248,7 @@ describe('TanStackCustomTableRow', () => {
</tbody>
</table>,
);
const row = screen.getByRole('row');
const row = container.querySelector('tr')!;
expect(row).toHaveClass('custom-row-class');
});
});

View File

@@ -1,4 +1,4 @@
import { screen, within } from 'tests/test-utils';
import { screen } from '@testing-library/react';
import type { TableColumnDef } from '../types';
import { defaultColumns, renderTanStackTable, type TestRow } from './testUtils';
@@ -14,35 +14,38 @@ const actionsColumn: TableColumnDef<TestRow> = {
width: { fixed: '96px', passLastColumnFill: true },
};
const colWidths = (): string[] =>
screen.getAllByTestId('tanstack-col').map((col) => col.style.width);
const colWidths = (container: HTMLElement): string[] =>
Array.from(container.querySelectorAll('colgroup col')).map(
(col) => (col as HTMLElement).style.width,
);
const isResizable = (columnId: string): boolean =>
const isResizable = (headerText: string): boolean =>
Boolean(
within(screen.getByTestId(`tanstack-header-${columnId}`)).queryByTitle(
'Drag to resize column',
),
screen
.getByText(headerText)
.closest('th')
?.querySelector('[title="Drag to resize column"]'),
);
describe('TanStackTable column fill', () => {
it('fills and locks the last column by default', () => {
renderTanStackTable();
const { container } = renderTanStackTable();
expect(colWidths().at(-1)).toBe('100%');
expect(isResizable('name')).toBe(true);
expect(isResizable('value')).toBe(false);
expect(colWidths(container).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', () => {
renderTanStackTable({
const { container } = renderTanStackTable({
props: { columns: [...defaultColumns, actionsColumn] },
});
const widths = colWidths();
const widths = colWidths(container);
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);
});
});

View File

@@ -1,11 +1,6 @@
import { useEffect, useState } from 'react';
import {
fireEvent,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UrlUpdateEvent } from 'nuqs/adapters/testing';
import TanStackTable from '../index';
@@ -164,7 +159,14 @@ describe('TanStackTableView Integration', () => {
});
// Find page 2 button/link within pagination navigation
await user.click(screen.getByTestId('pagination-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 waitFor(() => {
const lastPage = onUrlUpdate.mock.calls
@@ -325,7 +327,9 @@ describe('TanStackTableView Integration', () => {
});
// Page size combobox trigger should be visible by default (button with aria-haspopup)
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
const comboboxTrigger = document.querySelector(
'button[aria-haspopup="dialog"]',
);
expect(comboboxTrigger).toBeInTheDocument();
});
@@ -345,7 +349,9 @@ describe('TanStackTableView Integration', () => {
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
const comboboxTrigger = document.querySelector(
'button[aria-haspopup="dialog"]',
);
expect(comboboxTrigger).toBeInTheDocument();
});
@@ -365,7 +371,9 @@ describe('TanStackTableView Integration', () => {
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
const comboboxTrigger = screen.queryByTestId('pagination-page-size');
const comboboxTrigger = document.querySelector(
'button[aria-haspopup="dialog"]',
);
expect(comboboxTrigger).not.toBeInTheDocument();
});
@@ -383,7 +391,14 @@ describe('TanStackTableView Integration', () => {
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
await user.click(screen.getByTestId('pagination-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 waitFor(() => {
expect(onPageChange).toHaveBeenCalledWith(2);
@@ -405,7 +420,15 @@ describe('TanStackTableView Integration', () => {
},
});
const comboboxTrigger = await screen.findByTestId('pagination-page-size');
await waitFor(() => {
expect(
document.querySelector('button[aria-haspopup="dialog"]'),
).toBeInTheDocument();
});
const comboboxTrigger = document.querySelector(
'button[aria-haspopup="dialog"]',
) as HTMLElement;
await user.click(comboboxTrigger);
// Select a different page size option
@@ -453,7 +476,14 @@ describe('TanStackTableView Integration', () => {
});
// Navigate to page 2
await user.click(screen.getByTestId('pagination-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 waitFor(() => {
const lastPage = onUrlUpdate.mock.calls
@@ -464,7 +494,10 @@ describe('TanStackTableView Integration', () => {
});
// Change page size
await user.click(screen.getByTestId('pagination-page-size'));
const comboboxTrigger = document.querySelector(
'button[aria-haspopup="dialog"]',
) as HTMLElement;
await user.click(comboboxTrigger);
await user.type(
await screen.findByTestId('pagination-page-size-search'),
@@ -654,7 +687,6 @@ describe('TanStackTableView Integration', () => {
renderTanStackTable({
props: {
isRowActive: (row) => row.id === '1',
getRowTestId: (row) => `row-${row.id}`,
},
});
@@ -663,7 +695,9 @@ describe('TanStackTableView Integration', () => {
});
// Find the row containing Item 1 and check for active class
expect(screen.getByTestId('row-1')).toHaveClass('tableRowActive');
const cell = screen.getByText('Item 1');
const row = cell.closest('tr');
expect(row).toHaveClass('tableRowActive');
});
it('calls onRowClick with isActive: true when clicking the active row', async () => {
@@ -810,8 +844,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] = within(screen.getByRole('table')).getAllByRole('rowgroup');
expect(within(tbody).getAllByRole('row')).toHaveLength(4);
const tbody = screen.getByRole('table').querySelector('tbody');
expect(tbody?.querySelectorAll('tr')).toHaveLength(4);
});
});
@@ -962,9 +996,7 @@ describe('TanStackTableView Integration', () => {
describe('hasSingleColumn — gates the Remove popover per-column', () => {
const hasSingleColumnFlagPresent = (): boolean =>
screen
.getAllByTestId(/^tanstack-header-/)
.some((th) => th.getAttribute('data-single-column') === 'true');
Boolean(document.querySelector('th[data-single-column="true"]'));
it('is true when only one non-pinned column exists', async () => {
renderTanStackTable({

View File

@@ -21,7 +21,6 @@ export default function TypicalOverlayScrollbar({
options={options}
style={style}
className="overlay-scrollbar"
data-testid="overlay-scrollbar"
data-overlayscrollbars-initialize
>
{children}

View File

@@ -1,4 +1,5 @@
import { render, screen } from 'tests/test-utils';
import { screen } from '@testing-library/react';
import { render } from 'tests/test-utils';
import ValueGraph from '../index';
import { getBackgroundColorAndThresholdCheck } from '../utils';
@@ -94,11 +95,12 @@ describe('ValueGraph', () => {
isConflictingThresholds: false,
});
render(<ValueGraph value="42" rawValue={42} thresholds={[]} />);
const { container } = render(
<ValueGraph value="42" rawValue={42} thresholds={[]} />,
);
expect(screen.getByTestId('value-graph-container')).toHaveStyle({
backgroundColor: 'blue',
});
const containerElement = container.querySelector('.value-graph-container');
expect(containerElement).toHaveStyle({ backgroundColor: 'blue' });
});
it('displays conflicting thresholds indicator when multiple thresholds match', () => {

View File

@@ -92,7 +92,6 @@ function ValueGraph({
<div
ref={containerRef}
className="value-graph-container"
data-testid="value-graph-container"
style={{
backgroundColor:
threshold.thresholdFormat === 'Background'

View File

@@ -1,4 +1,5 @@
import { render, screen, userEvent } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { YAxisCategoryNames } from '../constants';
import { UniversalYAxisUnit, YAxisSource } from '../types';
@@ -12,7 +13,7 @@ describe('YAxisUnitSelector', () => {
beforeEach(() => {
mockOnChange.mockClear();
user = userEvent.setup();
user = userEvent.setup({ pointerEventsCheck: 0 });
});
it('renders with default placeholder', () => {

View File

@@ -111,7 +111,7 @@ describe('CmdKPalette', () => {
});
it('clicking a navigation item navigates to the correct route', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<CmdKPalette userRole="ADMIN" />);
await user.type(

View File

@@ -1,17 +0,0 @@
import { RuletypesAlertTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { DataSource } from 'types/common/queryBuilder';
import { dataSourceForAlertType } from '../alerts';
describe('dataSourceForAlertType', () => {
it.each([
[RuletypesAlertTypeDTO.METRIC_BASED_ALERT, DataSource.METRICS],
[RuletypesAlertTypeDTO.LOGS_BASED_ALERT, DataSource.LOGS],
[RuletypesAlertTypeDTO.TRACES_BASED_ALERT, DataSource.TRACES],
[RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT, DataSource.TRACES],
[RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT, DataSource.TRACES],
[undefined, DataSource.METRICS],
])('maps %s to %s', (alertType, dataSource) => {
expect(dataSourceForAlertType(alertType)).toBe(dataSource);
});
});

View File

@@ -8,7 +8,6 @@ export const ALERTS_DATA_SOURCE_MAP: Record<AlertTypes, DataSource> = {
[AlertTypes.LOGS_BASED_ALERT]: DataSource.LOGS,
[AlertTypes.TRACES_BASED_ALERT]: DataSource.TRACES,
[AlertTypes.EXCEPTIONS_BASED_ALERT]: DataSource.TRACES,
[AlertTypes.AI_TRACES_BASED_ALERT]: DataSource.TRACES,
};
export function dataSourceForAlertType(
@@ -19,7 +18,6 @@ export function dataSourceForAlertType(
return DataSource.LOGS;
case RuletypesAlertTypeDTO.TRACES_BASED_ALERT:
case RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT:
case RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT:
return DataSource.TRACES;
default:
return DataSource.METRICS;

View File

@@ -144,7 +144,6 @@ 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}

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<ActionsSection actions={[OPEN_ALERT]} messageId="message-2" />,
undefined,

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<ActionsSection
actions={[

View File

@@ -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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<ActivityGroup items={steps} />);
const toggle = screen.getByTestId('ai-activity-toggle');

View File

@@ -1,8 +1,6 @@
@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);

View File

@@ -54,7 +54,7 @@ describe('ComposerCaret', () => {
});
it('draws its caret while the composer has focus', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
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();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<Composer />);
const composer = screen.getByTestId<HTMLTextAreaElement>('composer');
await user.type(composer, 'checkout latency');

View File

@@ -45,7 +45,6 @@ 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">

View File

@@ -26,7 +26,7 @@ describe('ChatInput composer', () => {
});
it('lets the user type but not send while sending is blocked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSend = jest.fn() as jest.MockedFunction<
ComponentProps<typeof ChatInput>['onSend']
>;

Some files were not shown because too many files have changed in this diff Show More