mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-25 09:40:59 +00:00
Compare commits
19 Commits
issue_nerv
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af3fd93339 | ||
|
|
22a65c4f74 | ||
|
|
fa1dbe25cb | ||
|
|
a7d8245f69 | ||
|
|
a51f657ee0 | ||
|
|
aaf3d4a20a | ||
|
|
54158d633d | ||
|
|
09d905edc4 | ||
|
|
d473d022b0 | ||
|
|
1664c29cf4 | ||
|
|
f4bc90da34 | ||
|
|
02de020642 | ||
|
|
570e622a46 | ||
|
|
381cda6821 | ||
|
|
9dbe4db00e | ||
|
|
da35d99714 | ||
|
|
f955bb952a | ||
|
|
cb0adcc618 | ||
|
|
b14b634bce |
@@ -9,12 +9,14 @@ 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` computes the accessibility tree on every call and is the slowest query.
|
||||
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@testing-library/user-event` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
|
||||
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
|
||||
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
|
||||
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.
|
||||
|
||||
@@ -15,3 +15,4 @@ paths:
|
||||
- When defining types, keep the structure of file to have any constants and variables first, then exported types and exported methods and then finally the unexported types and methods.
|
||||
- Never import types or other modules in migration files, duplicate the required type or method to keep migration free from changes.
|
||||
- Always run the gofmt tool for formating beforing commiting any changes.
|
||||
- **Never copy through a pointer dereference** (`copied := *original`). It copies only the top level: pointer, slice and map fields stay shared, so changing the copy can change the original. Use the type's `Copy()` when it has one (`QueryBuilderFormula.Copy`); otherwise create a new struct literal from the fields you need. A `Copy()` itself may dereference, as long as it then replaces every pointer, slice and map field.
|
||||
|
||||
1011
docs/api/openapi.yml
1011
docs/api/openapi.yml
File diff suppressed because it is too large
Load Diff
@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
|
||||
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
|
||||
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
|
||||
every interactive element.
|
||||
5. **Verify** before reporting done:
|
||||
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
|
||||
```bash
|
||||
pnpm tsgo --noEmit
|
||||
pnpm oxlint src/pages/<Feature>
|
||||
|
||||
@@ -552,6 +552,7 @@
|
||||
],
|
||||
"rules": {
|
||||
"import/first": "off",
|
||||
"signoz/no-dom-node-access": "error",
|
||||
// Should ignore due to mocks
|
||||
"signoz/no-navigator-clipboard": "off",
|
||||
// Tests can use navigator.clipboard directly,
|
||||
|
||||
@@ -176,6 +176,7 @@ const preview: Preview = {
|
||||
'AI Observability',
|
||||
['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
|
||||
'Noz',
|
||||
['Overview', 'Modal', 'Panel'],
|
||||
'Metering',
|
||||
['Cost Meter', 'Usage Explorer'],
|
||||
'Messaging Queues',
|
||||
|
||||
@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
|
||||
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
|
||||
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
|
||||
|
||||
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
|
||||
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
|
||||
- Between gates, after an edit, run at most the one test file that covers it.
|
||||
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
|
||||
|
||||
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
|
||||
- Run `pnpm tsgo --noEmit`
|
||||
- Run `pnpm lint:js --quiet` to find critical errors
|
||||
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
|
||||
- Run `pnpm build`
|
||||
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
|
||||
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
|
||||
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
|
||||
- Fixed ALL resulting errors
|
||||
|
||||
|
||||
@@ -67,6 +67,8 @@ const config: Config.InitialOptions = {
|
||||
testPathIgnorePatterns: ['/node_modules/', '/public/'],
|
||||
moduleDirectories: ['node_modules', 'src'],
|
||||
testEnvironment: '<rootDir>/jest.environment.cjs',
|
||||
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
|
||||
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
statements: 80,
|
||||
|
||||
@@ -16,6 +16,24 @@ class JSDOMWithRequestEnvironment extends TestEnvironment {
|
||||
Object.defineProperty(this, 'signal', { value: signal ?? super.signal });
|
||||
}
|
||||
};
|
||||
|
||||
// Library CSS (antd's runtime styles, CodeMirror's theme, @signozhq/ui's
|
||||
// injected modules) stays out of the document, as the app's own stylesheets
|
||||
// already do through moduleNameMapper. jsdom matches every rule on each
|
||||
// getComputedStyle call, which made a role query take up to half a second.
|
||||
// rc-util adds and removes an empty style tag to find its container, so a
|
||||
// dropped tag must also be removable.
|
||||
const { Node, HTMLStyleElement, document } = this.global;
|
||||
for (const method of ['appendChild', 'insertBefore', 'removeChild']) {
|
||||
const original = Node.prototype[method];
|
||||
Node.prototype[method] = function (node, ...rest) {
|
||||
const isDroppedStyle =
|
||||
this === document.head &&
|
||||
node instanceof HTMLStyleElement &&
|
||||
node.parentNode !== this;
|
||||
return isDroppedStyle ? node : original.call(this, node, ...rest);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,19 @@ if (!HTMLElement.prototype.scrollIntoView) {
|
||||
HTMLElement.prototype.scrollIntoView = function (): void {};
|
||||
}
|
||||
|
||||
// jsdom has no elementFromPoint; CodeMirror calls it on mousedown to place the cursor.
|
||||
if (!document.elementFromPoint) {
|
||||
document.elementFromPoint = (): Element | null => null;
|
||||
}
|
||||
|
||||
// jsdom Ranges have no layout; CodeMirror measures text through them on click.
|
||||
if (!Range.prototype.getClientRects) {
|
||||
Range.prototype.getClientRects = (): DOMRectList =>
|
||||
document.body.getClientRects();
|
||||
Range.prototype.getBoundingClientRect = (): DOMRect =>
|
||||
document.body.getBoundingClientRect();
|
||||
}
|
||||
|
||||
// jsdom doesn't implement the Pointer Capture API, which Radix UI primitives
|
||||
// (e.g. @signozhq/ui Select) call when opening. Stub them so those components
|
||||
// can be exercised in tests.
|
||||
@@ -120,29 +133,9 @@ if (typeof globalThis.DOMRect === 'undefined') {
|
||||
};
|
||||
}
|
||||
|
||||
// Patch getComputedStyle to handle CSS parsing errors from @signozhq/* packages.
|
||||
// These packages inject CSS at import time via style-inject / vite-plugin-css-injected-by-js.
|
||||
// jsdom's nwsapi cannot parse some of the injected selectors (e.g. Tailwind's :animate-in),
|
||||
// causing SyntaxErrors during getComputedStyle / getByRole calls.
|
||||
const _origGetComputedStyle = window.getComputedStyle;
|
||||
window.getComputedStyle = function (
|
||||
elt: Element,
|
||||
pseudoElt?: string | null,
|
||||
): CSSStyleDeclaration {
|
||||
try {
|
||||
return _origGetComputedStyle.call(window, elt, pseudoElt);
|
||||
} catch {
|
||||
// Return a minimal CSSStyleDeclaration so callers (testing-library, Radix UI)
|
||||
// see the element as visible and without animations.
|
||||
return {
|
||||
display: '',
|
||||
visibility: '',
|
||||
opacity: '1',
|
||||
animationName: 'none',
|
||||
getPropertyValue: () => '',
|
||||
} as unknown as CSSStyleDeclaration;
|
||||
}
|
||||
};
|
||||
jest.mock('@testing-library/user-event', () =>
|
||||
jest.requireActual('tests/userEventWithDefaults'),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"@sentry/vite-plugin": "5.3.0",
|
||||
"@signozhq/design-tokens": "2.8.0",
|
||||
"@signozhq/icons": "0.4.0",
|
||||
"@signozhq/noz-client": "1.13.0",
|
||||
"@signozhq/ui": "0.4.0-rc.5",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
|
||||
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const message = (name) =>
|
||||
`Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`;
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-dom-node-access',
|
||||
valid: [
|
||||
{
|
||||
name: 'Testing Library queries',
|
||||
code: "within(screen.getByTestId('row')).getByText('Name');",
|
||||
},
|
||||
{
|
||||
name: 'a query method that is not called',
|
||||
code:
|
||||
'jest.spyOn(document, "querySelector");\nconst q = Element.prototype.closest;',
|
||||
},
|
||||
{
|
||||
name: 'computed access',
|
||||
code: "const name = 'closest';\nel[name]('tr');",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'querySelector on the container',
|
||||
code: "container.querySelector('.row');",
|
||||
errors: [{ message: message('querySelector'), line: 1, column: 11 }],
|
||||
},
|
||||
{
|
||||
name: 'closest after a screen query',
|
||||
code: "screen.getByText('Name').closest('tr');",
|
||||
errors: [{ message: message('closest'), line: 1, column: 26 }],
|
||||
},
|
||||
{
|
||||
name: 'optional call',
|
||||
code: "row?.querySelectorAll('td');",
|
||||
errors: [{ message: message('querySelectorAll'), line: 1, column: 6 }],
|
||||
},
|
||||
{
|
||||
name: 'traversal property',
|
||||
code: 'expect(cell.parentElement).toBeVisible();',
|
||||
errors: [{ message: message('parentElement'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a DOM node',
|
||||
code: "expect(screen.getByTestId('list').children).toHaveLength(2);",
|
||||
errors: [{ message: message('children'), line: 1, column: 35 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a data tree',
|
||||
code: 'expect(tree.children).toHaveLength(2);',
|
||||
errors: [{ message: message('children'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'document lookup by id',
|
||||
code: "document.getElementById('root');",
|
||||
errors: [{ message: message('getElementById'), line: 1, column: 10 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Rule: no-dom-node-access
|
||||
*
|
||||
* Tests find elements through Testing Library (`screen`, `within`), not by
|
||||
* walking the DOM. Flags calls to DOM query methods and reads of node
|
||||
* traversal properties:
|
||||
* container.querySelector('.row')
|
||||
* screen.getByText('Name').closest('tr')
|
||||
* cell.parentElement
|
||||
* list.children
|
||||
*
|
||||
* A non-DOM `children` read (a data tree, React props) disables the rule on
|
||||
* that line with a reason.
|
||||
*/
|
||||
|
||||
const QUERY_METHODS = new Set([
|
||||
'querySelector',
|
||||
'querySelectorAll',
|
||||
'closest',
|
||||
'getElementById',
|
||||
'getElementsByClassName',
|
||||
'getElementsByTagName',
|
||||
'getElementsByName',
|
||||
]);
|
||||
|
||||
const TRAVERSAL_PROPERTIES = new Set([
|
||||
'parentElement',
|
||||
'parentNode',
|
||||
'firstChild',
|
||||
'lastChild',
|
||||
'firstElementChild',
|
||||
'lastElementChild',
|
||||
'nextSibling',
|
||||
'previousSibling',
|
||||
'nextElementSibling',
|
||||
'previousElementSibling',
|
||||
'childNodes',
|
||||
'children',
|
||||
]);
|
||||
|
||||
export default {
|
||||
create(context) {
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
if (node.computed || node.property.type !== 'Identifier') {
|
||||
return;
|
||||
}
|
||||
const { name } = node.property;
|
||||
const isCall =
|
||||
node.parent?.type === 'CallExpression' && node.parent.callee === node;
|
||||
if ((isCall && QUERY_METHODS.has(name)) || TRAVERSAL_PROPERTIES.has(name)) {
|
||||
context.report({
|
||||
node: node.property,
|
||||
message: `Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
|
||||
import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
|
||||
import noTextCss from './rules/no-text-css.mjs';
|
||||
import requireDisableReason from './rules/require-disable-reason.mjs';
|
||||
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -39,5 +40,6 @@ export default {
|
||||
'no-direct-react-router-import': noDirectReactRouterImport,
|
||||
'no-text-css': noTextCss,
|
||||
'require-disable-reason': requireDisableReason,
|
||||
'no-dom-node-access': noDomNodeAccess,
|
||||
},
|
||||
};
|
||||
|
||||
16
frontend/pnpm-lock.yaml
generated
16
frontend/pnpm-lock.yaml
generated
@@ -82,6 +82,9 @@ importers:
|
||||
'@signozhq/icons':
|
||||
specifier: 0.4.0
|
||||
version: 0.4.0
|
||||
'@signozhq/noz-client':
|
||||
specifier: 1.13.0
|
||||
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
|
||||
'@signozhq/ui':
|
||||
specifier: 0.4.0-rc.5
|
||||
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
@@ -3248,6 +3251,13 @@ packages:
|
||||
'@signozhq/icons@0.4.0':
|
||||
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
|
||||
|
||||
'@signozhq/noz-client@1.13.0':
|
||||
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
|
||||
peerDependencies:
|
||||
axios: ^1.20.0
|
||||
react: ^18.2.0
|
||||
react-query: ^3.39.3
|
||||
|
||||
'@signozhq/ui@0.4.0-rc.5':
|
||||
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
|
||||
peerDependencies:
|
||||
@@ -12373,6 +12383,12 @@ snapshots:
|
||||
|
||||
'@signozhq/icons@0.4.0': {}
|
||||
|
||||
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
|
||||
dependencies:
|
||||
axios: 1.21.1
|
||||
react: 18.2.0
|
||||
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
|
||||
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
|
||||
dependencies:
|
||||
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
|
||||
|
||||
@@ -321,8 +321,8 @@ const createTracesResponse = ({
|
||||
httpMethod: trace.httpMethod ?? httpMethods[index % httpMethods.length],
|
||||
responseStatusCode:
|
||||
trace.responseStatusCode ?? statusCodes[index % statusCodes.length],
|
||||
traceID: `trace-id-${index}`,
|
||||
spanID: `span-id-${index}`,
|
||||
trace_id: `trace-id-${index}`,
|
||||
span_id: `span-id-${index}`,
|
||||
},
|
||||
};
|
||||
})
|
||||
@@ -340,8 +340,8 @@ const createTracesResponse = ({
|
||||
durationNano: 1000000 + cumulativeIndex * 100000,
|
||||
httpMethod: httpMethods[cumulativeIndex % httpMethods.length],
|
||||
responseStatusCode: statusCodes[cumulativeIndex % statusCodes.length],
|
||||
traceID: `trace-id-${cumulativeIndex}`,
|
||||
spanID: `span-id-${cumulativeIndex}`,
|
||||
trace_id: `trace-id-${cumulativeIndex}`,
|
||||
span_id: `span-id-${cumulativeIndex}`,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* to resume, which each return a new executionId to open a fresh SSE stream.
|
||||
*
|
||||
* Types in this file re-use the OpenAPI-generated DTOs in
|
||||
* `src/api/ai-assistant/sigNozAIAssistantAPI.schemas.ts`.
|
||||
* `@signozhq/noz-client`.
|
||||
* Local types are defined only when the UI needs a different shape — for
|
||||
* example, the SSE event union adds a literal `type` discriminator that the
|
||||
* generated event DTOs leave loose.
|
||||
@@ -30,16 +30,11 @@ import rotateSession from 'api/v2/sessions/rotate/post';
|
||||
import afterLogin from 'AppRoutes/utils';
|
||||
import type {
|
||||
ActionResultResponseDTO,
|
||||
ApprovalEventDTO,
|
||||
ApproveResponseDTO,
|
||||
CancelResponseDTO,
|
||||
ClarificationEventDTO,
|
||||
ClarifyResponseDTO,
|
||||
ConversationEventDTO,
|
||||
CreateMessageResponseDTO,
|
||||
CreateThreadResponseDTO,
|
||||
DoneEventDTO,
|
||||
ErrorEventDTO,
|
||||
ExecutionStateDTO,
|
||||
FeedbackRatingDTO,
|
||||
ListThreadsApiV1AssistantThreadsGetArchived,
|
||||
@@ -47,20 +42,15 @@ import type {
|
||||
MessageContextDTO,
|
||||
MessageContextDTOSource,
|
||||
MessageContextDTOType,
|
||||
MessageEventDTO,
|
||||
MessageSummaryDTO,
|
||||
RegenerateResponseDTO,
|
||||
StatusEventDTO,
|
||||
ThinkingEventDTO,
|
||||
ThreadDetailResponseDTO,
|
||||
ThreadListResponseDTO,
|
||||
ThreadSummaryDTO,
|
||||
ChipDTO,
|
||||
ChipsResponseDTO,
|
||||
PageTypeDTO,
|
||||
ToolCallEventDTO,
|
||||
ToolResultEventDTO,
|
||||
} from './sigNozAIAssistantAPI.schemas';
|
||||
} from '@signozhq/noz-client';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
import {
|
||||
@@ -70,6 +60,10 @@ import {
|
||||
} from '../AIAPIInstance';
|
||||
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
|
||||
|
||||
import type { SSEEvent } from './sseEvent';
|
||||
|
||||
export type { SSEEvent };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE-only auth wrapper.
|
||||
//
|
||||
@@ -183,26 +177,6 @@ async function fetchSSEWithAuth(
|
||||
return res;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE event types
|
||||
//
|
||||
// The generated event DTOs each declare `type?: string` (loose). The UI needs
|
||||
// a discriminated union, so we intersect each variant with a string-literal
|
||||
// `type` to enable narrowing via `event.type === 'status'`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type SSEEvent =
|
||||
| (StatusEventDTO & { type: 'status' })
|
||||
| (MessageEventDTO & { type: 'message' })
|
||||
| (ThinkingEventDTO & { type: 'thinking' })
|
||||
| (ToolCallEventDTO & { type: 'tool_call' })
|
||||
| (ToolResultEventDTO & { type: 'tool_result' })
|
||||
| (ApprovalEventDTO & { type: 'approval' })
|
||||
| (ClarificationEventDTO & { type: 'clarification' })
|
||||
| (ErrorEventDTO & { type: 'error' })
|
||||
| (ConversationEventDTO & { type: 'conversation' })
|
||||
| (DoneEventDTO & { type: 'done' });
|
||||
|
||||
/** String-literal view of `ExecutionStateDTO` for ergonomic comparisons. */
|
||||
export type ExecutionState = `${ExecutionStateDTO}`;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
32
frontend/src/api/ai-assistant/sseEvent.ts
Normal file
32
frontend/src/api/ai-assistant/sseEvent.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type {
|
||||
ApprovalEventDTO,
|
||||
ClarificationEventDTO,
|
||||
ConversationEventDTO,
|
||||
DoneEventDTO,
|
||||
ErrorEventDTO,
|
||||
MessageEventDTO,
|
||||
StatusEventDTO,
|
||||
ThinkingEventDTO,
|
||||
ToolCallEventDTO,
|
||||
ToolResultEventDTO,
|
||||
} from '@signozhq/noz-client';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE event types
|
||||
//
|
||||
// The generated event DTOs each declare `type?: string` (loose). The UI needs
|
||||
// a discriminated union, so we intersect each variant with a string-literal
|
||||
// `type` to enable narrowing via `event.type === 'status'`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type SSEEvent =
|
||||
| (StatusEventDTO & { type: 'status' })
|
||||
| (MessageEventDTO & { type: 'message' })
|
||||
| (ThinkingEventDTO & { type: 'thinking' })
|
||||
| (ToolCallEventDTO & { type: 'tool_call' })
|
||||
| (ToolResultEventDTO & { type: 'tool_result' })
|
||||
| (ApprovalEventDTO & { type: 'approval' })
|
||||
| (ClarificationEventDTO & { type: 'clarification' })
|
||||
| (ErrorEventDTO & { type: 'error' })
|
||||
| (ConversationEventDTO & { type: 'conversation' })
|
||||
| (DoneEventDTO & { type: 'done' });
|
||||
@@ -17,13 +17,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -15,13 +15,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -14204,19 +14204,7 @@ export interface SpantypesTraceAITokensDTO {
|
||||
}
|
||||
|
||||
export interface SpantypesTraceAISummaryDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of model call spans: spans with gen_ai.request.model.
|
||||
*/
|
||||
modelCallCount: number;
|
||||
tokens: SpantypesTraceAITokensDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of tool call spans: spans with gen_ai.tool.name.
|
||||
*/
|
||||
toolCallCount: number;
|
||||
/**
|
||||
* @type number
|
||||
*/
|
||||
@@ -14644,266 +14632,6 @@ export interface SpantypesPostableWaterfallDTO {
|
||||
uncollapsedSpans?: string[] | null;
|
||||
}
|
||||
|
||||
export interface SpantypesSameNameSiblingStatsDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans in the group that are marked as errors.
|
||||
*/
|
||||
errorSpanCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Total own time of the group, in nanoseconds.
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans in the group, this span included.
|
||||
*/
|
||||
spanCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Span attributes. A span read by ID has all of them; a span in a list has only the selected ones.
|
||||
*/
|
||||
export type SpantypesSpanDTOAttributes = { [key: string]: unknown };
|
||||
|
||||
/**
|
||||
* Resource attributes. Always includes service.name. A span read by ID has all of them; a span in a list also has the selected ones.
|
||||
*/
|
||||
export type SpantypesSpanDTOResource = { [key: string]: string };
|
||||
|
||||
export interface SpantypesSpanDTO {
|
||||
/**
|
||||
* @type object
|
||||
* @description Span attributes. A span read by ID has all of them; a span in a list has only the selected ones.
|
||||
*/
|
||||
attributes: SpantypesSpanDTOAttributes;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Duration, in nanoseconds.
|
||||
*/
|
||||
duration_nano: number;
|
||||
/**
|
||||
* @type array
|
||||
* @description Span events. A span read by ID has all of them; a span in a list has none.
|
||||
*/
|
||||
events: SpantypesEventDTO[];
|
||||
/**
|
||||
* @type boolean
|
||||
* @description Whether the span is marked as an error.
|
||||
*/
|
||||
has_error: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description Span kind, for example Server, Client or Internal.
|
||||
*/
|
||||
kind_string: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description ID of the parent span. Empty for a root.
|
||||
*/
|
||||
parent_span_id: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description References to other spans: the parent as CHILD_OF, and each span link as FOLLOWS_FROM.
|
||||
*/
|
||||
references: SpantypesOtelSpanRefDTO[];
|
||||
/**
|
||||
* @type object
|
||||
* @description Resource attributes. Always includes service.name. A span read by ID has all of them; a span in a list also has the selected ones.
|
||||
*/
|
||||
resource: SpantypesSpanDTOResource;
|
||||
/**
|
||||
* @type string
|
||||
* @description HTTP or gRPC status code of the response, for example 404. Empty when the span has none.
|
||||
*/
|
||||
response_status_code: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
span_id: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description OpenTelemetry status code of the span.
|
||||
*/
|
||||
status_code_string: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Status message, usually the error text. Empty when the span has none.
|
||||
*/
|
||||
status_message: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Start time, in nanoseconds since the Unix epoch.
|
||||
*/
|
||||
timestamp: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
trace_id: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTextMatchDTO {
|
||||
/**
|
||||
* @type string
|
||||
* @description Where the word was found: name, status_message, attributes.<name>, resource.<name> or events[<index>].
|
||||
*/
|
||||
field: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The word with some of the text around it.
|
||||
*/
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTreeStatsDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of direct children.
|
||||
*/
|
||||
childCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of ancestors in a row, starting at the parent, that are marked as errors. On an error span it shows how far up the error spread.
|
||||
*/
|
||||
errorAncestorCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Depth in the trace: 0 for a root, 1 for its children, and so on.
|
||||
*/
|
||||
level: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Time spent in the span itself, in nanoseconds: its duration minus the time its children cover.
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @description Totals for the spans that share this span's name and parent, this span included. Omitted when no other span does.
|
||||
*/
|
||||
sameNameSiblings?: SpantypesSameNameSiblingStatsDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans below this one, at any depth.
|
||||
*/
|
||||
subtreeSpanCount: number;
|
||||
}
|
||||
|
||||
export enum SpantypesUnmarkedFailureReasonDTO {
|
||||
http_4xx = 'http_4xx',
|
||||
http_5xx = 'http_5xx',
|
||||
grpc_status = 'grpc_status',
|
||||
exception_event = 'exception_event',
|
||||
}
|
||||
export interface SpantypesSpanItemDTO {
|
||||
/**
|
||||
* @type array
|
||||
* @description Where the words of the query were found, up to three places. A list does not return all attributes or any events, so this is how to see why a span matched. Omitted when the query has no words.
|
||||
*/
|
||||
matches?: SpantypesSpanTextMatchDTO[];
|
||||
span: SpantypesSpanDTO;
|
||||
/**
|
||||
* @description Numbers computed from the span's place in the trace.
|
||||
*/
|
||||
treeStats: SpantypesSpanTreeStatsDTO;
|
||||
/**
|
||||
* @description Why the span counts as failed although it is not marked as an error. Omitted for every other span.
|
||||
*/
|
||||
unmarkedFailureReason?: SpantypesUnmarkedFailureReasonDTO;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanListDTO {
|
||||
/**
|
||||
* @type array
|
||||
* @description The spans of this page.
|
||||
*/
|
||||
items: SpantypesSpanItemDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans that match the request, across all pages.
|
||||
*/
|
||||
total: number;
|
||||
/**
|
||||
* @type array
|
||||
* @description Reasons the result may be incomplete, for example a query key that is not known or a selected field that no returned span has. Omitted when there are none.
|
||||
*/
|
||||
warnings?: string[];
|
||||
}
|
||||
|
||||
export enum SpantypesSpanListViewDTO {
|
||||
error_origins = 'error_origins',
|
||||
unmarked_failures = 'unmarked_failures',
|
||||
time_spent = 'time_spent',
|
||||
ai_usage = 'ai_usage',
|
||||
links = 'links',
|
||||
}
|
||||
export interface SpantypesTraceServiceStatsDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans of the service that are marked as errors.
|
||||
*/
|
||||
errorSpanCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Total own time of the service's spans, in nanoseconds.
|
||||
*/
|
||||
ownTimeNano: number;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
serviceName: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
* @description Number of spans of the service.
|
||||
*/
|
||||
spanCount: number;
|
||||
}
|
||||
|
||||
export interface SpantypesTraceHighlightsDTO {
|
||||
/**
|
||||
* @description The spans with the highest gen_ai cost or token usage. First page of the ai_usage view of the span list. Empty for a trace where no span carries that usage.
|
||||
*/
|
||||
aiUsage?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description The spans where an error started. First page of the error_origins view of the span list.
|
||||
*/
|
||||
errorOrigins?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description Spans that link to other spans. First page of the links view of the span list.
|
||||
*/
|
||||
links?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type array
|
||||
* @description Totals for each service of the trace, highest own time first.
|
||||
*/
|
||||
services: SpantypesTraceServiceStatsDTO[];
|
||||
/**
|
||||
* @description Where the time went, same-name siblings counted as one. First page of the time_spent view of the span list.
|
||||
*/
|
||||
timeSpent?: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @description Spans that failed without being marked as errors. First page of the unmarked_failures view of the span list.
|
||||
*/
|
||||
unmarkedFailures?: SpantypesSpanListDTO;
|
||||
}
|
||||
|
||||
export interface SpantypesUpdatableSpanMapperDTO {
|
||||
config?: SpantypesSpanMapperConfigDTO;
|
||||
/**
|
||||
@@ -15891,7 +15619,7 @@ export type GetFieldsValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
@@ -16369,197 +16097,6 @@ export type GetTraceAggregations200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetTraceHighlightsPathParameters = {
|
||||
traceID: string;
|
||||
};
|
||||
export type GetTraceHighlightsParams = {
|
||||
/**
|
||||
* @type array
|
||||
* @description The lists to return, each named by its view. Default: all of them.
|
||||
*/
|
||||
views?: SpantypesSpanListViewDTO[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans in each list. Default: 10. Maximum: 1000.
|
||||
*/
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type GetTraceHighlights200 = {
|
||||
data: SpantypesTraceHighlightsDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListTraceSpansPathParameters = {
|
||||
traceID: string;
|
||||
};
|
||||
export type ListTraceSpansParams = {
|
||||
/**
|
||||
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
|
||||
*/
|
||||
selectFields?: string[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to skip. Default: 0.
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to return. Default: 50. Maximum: 1000.
|
||||
*/
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type ListTraceSpans200 = {
|
||||
data: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetTraceSpanPathParameters = {
|
||||
traceID: string;
|
||||
spanID: string;
|
||||
};
|
||||
export type GetTraceSpan200 = {
|
||||
data: SpantypesSpanDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListTraceSpanAncestorsPathParameters = {
|
||||
traceID: string;
|
||||
spanID: string;
|
||||
};
|
||||
export type ListTraceSpanAncestorsParams = {
|
||||
/**
|
||||
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
|
||||
*/
|
||||
selectFields?: string[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to skip. Default: 0.
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to return. Default: 50. Maximum: 1000.
|
||||
*/
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type ListTraceSpanAncestors200 = {
|
||||
data: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListTraceSpanChildrenPathParameters = {
|
||||
traceID: string;
|
||||
spanID: string;
|
||||
};
|
||||
export type ListTraceSpanChildrenParams = {
|
||||
/**
|
||||
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
|
||||
*/
|
||||
selectFields?: string[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to skip. Default: 0.
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to return. Default: 50. Maximum: 1000.
|
||||
*/
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type ListTraceSpanChildren200 = {
|
||||
data: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListTraceSpanDescendantsPathParameters = {
|
||||
traceID: string;
|
||||
spanID: string;
|
||||
};
|
||||
export type ListTraceSpanDescendantsParams = {
|
||||
/**
|
||||
* @description A quick filter on the spans the route covers. Without it every span the route covers is returned, in the route's own order. With it only the spans of that kind are returned, in that kind's order. error_origins: the spans where an error started, meaning error spans with no failing child, by start time. unmarked_failures: spans that failed without being marked as errors (a 4xx or 5xx response, a gRPC status other than OK, or an exception event), by start time. time_spent: one span for each group of same-name siblings, by the group's total own time. ai_usage: the spans that carry gen_ai token or cost usage, by cost, or by tokens when none has a cost; each includes those attributes. links: the spans that link to other spans, by start time.
|
||||
*/
|
||||
view?: SpantypesSpanListViewDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description Returns only the spans that match. Takes words, a filter expression, or both, for example: worldpay AND has_error = true. Words are matched, ignoring case, against the span name, status message, attributes, resource attributes and events. A filter expression uses the keys of a span, such as kind_string or has_error.
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* @type array
|
||||
* @description Attributes and resource attributes to include on each span, for example http.route or resource.k8s.pod.name. Without it a span includes only service.name. A field that no returned span has is listed in warnings.
|
||||
*/
|
||||
selectFields?: string[];
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to skip. Default: 0.
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @description Number of spans to return. Default: 50. Maximum: 1000.
|
||||
*/
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export type ListTraceSpanDescendants200 = {
|
||||
data: SpantypesSpanListDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetTraceSummaryPathParameters = {
|
||||
traceID: string;
|
||||
};
|
||||
@@ -17699,7 +17236,7 @@ export type GetRuleHistoryFilterValuesParams = {
|
||||
searchText?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description The key whose values to return, such as service.name. A context prefix such as resource.service.name sets fieldContext when it is empty.
|
||||
* @description The key whose values to return, such as service.name. With fieldContext set, it is the stored name as is. Otherwise a context prefix such as resource.service.name sets the context and a type suffix such as service.name:string sets fieldDataType when that is empty; as in filter expressions, a prefixed name also matches a key stored under the full name, whose values come first: log.level returns values of a key named log.level, then of the log field level.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
|
||||
@@ -22,11 +22,6 @@ import type {
|
||||
GetFlamegraphPathParameters,
|
||||
GetTraceAggregations200,
|
||||
GetTraceAggregationsPathParameters,
|
||||
GetTraceHighlights200,
|
||||
GetTraceHighlightsParams,
|
||||
GetTraceHighlightsPathParameters,
|
||||
GetTraceSpan200,
|
||||
GetTraceSpanPathParameters,
|
||||
GetTraceSummary200,
|
||||
GetTraceSummaryPathParameters,
|
||||
GetTraceThread200,
|
||||
@@ -34,18 +29,6 @@ import type {
|
||||
GetTraceThreadPathParameters,
|
||||
GetWaterfallV4200,
|
||||
GetWaterfallV4PathParameters,
|
||||
ListTraceSpanAncestors200,
|
||||
ListTraceSpanAncestorsParams,
|
||||
ListTraceSpanAncestorsPathParameters,
|
||||
ListTraceSpanChildren200,
|
||||
ListTraceSpanChildrenParams,
|
||||
ListTraceSpanChildrenPathParameters,
|
||||
ListTraceSpanDescendants200,
|
||||
ListTraceSpanDescendantsParams,
|
||||
ListTraceSpanDescendantsPathParameters,
|
||||
ListTraceSpans200,
|
||||
ListTraceSpansParams,
|
||||
ListTraceSpansPathParameters,
|
||||
RenderErrorResponseDTO,
|
||||
SpantypesPostableFlamegraphDTO,
|
||||
SpantypesPostableTraceAggregationsDTO,
|
||||
@@ -176,710 +159,7 @@ export const useGetTraceAggregations = <
|
||||
return useMutation(getGetTraceAggregationsMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Returns the spans to look at, for a trace of any size: per-service totals and the first spans of each view of the span list. views names the lists to return; without it all of them are returned. Read more of a list from the span list with the view of the same name. The totals of the trace come from the trace summary.
|
||||
* @summary Get highlights of a trace
|
||||
*/
|
||||
export const getTraceHighlights = (
|
||||
{ traceID }: GetTraceHighlightsPathParameters,
|
||||
params?: GetTraceHighlightsParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<GetTraceHighlights200>({
|
||||
url: `/api/v1/traces/${traceID}/highlights`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getGetTraceHighlightsQueryKey = (
|
||||
{ traceID }: GetTraceHighlightsPathParameters,
|
||||
params?: GetTraceHighlightsParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/v1/traces/${traceID}/highlights`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getGetTraceHighlightsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getTraceHighlights>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: GetTraceHighlightsPathParameters,
|
||||
params?: GetTraceHighlightsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceHighlights>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetTraceHighlightsQueryKey({ traceID }, params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof getTraceHighlights>>
|
||||
> = ({ signal }) => getTraceHighlights({ traceID }, params, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: traceID !== null && traceID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceHighlights>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type GetTraceHighlightsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getTraceHighlights>>
|
||||
>;
|
||||
export type GetTraceHighlightsQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Get highlights of a trace
|
||||
*/
|
||||
|
||||
export function useGetTraceHighlights<
|
||||
TData = Awaited<ReturnType<typeof getTraceHighlights>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: GetTraceHighlightsPathParameters,
|
||||
params?: GetTraceHighlightsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceHighlights>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getGetTraceHighlightsQueryOptions(
|
||||
{ traceID },
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Get highlights of a trace
|
||||
*/
|
||||
export const invalidateGetTraceHighlights = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID }: GetTraceHighlightsPathParameters,
|
||||
params?: GetTraceHighlightsParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getGetTraceHighlightsQueryKey({ traceID }, params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of the spans of a trace, in tree order from the top: a span is followed by the spans below it. view keeps only the spans of one kind, query narrows them, and selectFields names the attributes to fill. Values are returned whole.
|
||||
* @summary List spans of a trace
|
||||
*/
|
||||
export const listTraceSpans = (
|
||||
{ traceID }: ListTraceSpansPathParameters,
|
||||
params?: ListTraceSpansParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListTraceSpans200>({
|
||||
url: `/api/v1/traces/${traceID}/spans`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListTraceSpansQueryKey = (
|
||||
{ traceID }: ListTraceSpansPathParameters,
|
||||
params?: ListTraceSpansParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/v1/traces/${traceID}/spans`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getListTraceSpansQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listTraceSpans>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: ListTraceSpansPathParameters,
|
||||
params?: ListTraceSpansParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpans>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getListTraceSpansQueryKey({ traceID }, params);
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof listTraceSpans>>> = ({
|
||||
signal,
|
||||
}) => listTraceSpans({ traceID }, params, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: traceID !== null && traceID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpans>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListTraceSpansQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listTraceSpans>>
|
||||
>;
|
||||
export type ListTraceSpansQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List spans of a trace
|
||||
*/
|
||||
|
||||
export function useListTraceSpans<
|
||||
TData = Awaited<ReturnType<typeof listTraceSpans>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: ListTraceSpansPathParameters,
|
||||
params?: ListTraceSpansParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpans>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListTraceSpansQueryOptions(
|
||||
{ traceID },
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List spans of a trace
|
||||
*/
|
||||
export const invalidateListTraceSpans = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID }: ListTraceSpansPathParameters,
|
||||
params?: ListTraceSpansParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListTraceSpansQueryKey({ traceID }, params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns one span with every attribute, resource attribute and event. Values are returned whole. It returns only the stored span: its tree stats come with it in any span list, and the spans around it come from the children, descendants and ancestors routes.
|
||||
* @summary Get span of a trace
|
||||
*/
|
||||
export const getTraceSpan = (
|
||||
{ traceID, spanID }: GetTraceSpanPathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<GetTraceSpan200>({
|
||||
url: `/api/v1/traces/${traceID}/spans/${spanID}`,
|
||||
method: 'GET',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getGetTraceSpanQueryKey = ({
|
||||
traceID,
|
||||
spanID,
|
||||
}: GetTraceSpanPathParameters) => {
|
||||
return [`/api/v1/traces/${traceID}/spans/${spanID}`] as const;
|
||||
};
|
||||
|
||||
export const getGetTraceSpanQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getTraceSpan>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: GetTraceSpanPathParameters,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSpan>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetTraceSpanQueryKey({ traceID, spanID });
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getTraceSpan>>> = ({
|
||||
signal,
|
||||
}) => getTraceSpan({ traceID, spanID }, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled:
|
||||
traceID !== null &&
|
||||
traceID !== undefined &&
|
||||
spanID !== null &&
|
||||
spanID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSpan>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type GetTraceSpanQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getTraceSpan>>
|
||||
>;
|
||||
export type GetTraceSpanQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Get span of a trace
|
||||
*/
|
||||
|
||||
export function useGetTraceSpan<
|
||||
TData = Awaited<ReturnType<typeof getTraceSpan>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: GetTraceSpanPathParameters,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSpan>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getGetTraceSpanQueryOptions({ traceID, spanID }, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Get span of a trace
|
||||
*/
|
||||
export const invalidateGetTraceSpan = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID, spanID }: GetTraceSpanPathParameters,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getGetTraceSpanQueryKey({ traceID, spanID }) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of the spans above a span: the chain of parents from the span up to its root, the parent first, and nothing from other branches. The span itself is not included. It takes the same parameters as the span list. The list is empty for a root, and stops where a parent was never received.
|
||||
* @summary List ancestors of a span
|
||||
*/
|
||||
export const listTraceSpanAncestors = (
|
||||
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
|
||||
params?: ListTraceSpanAncestorsParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListTraceSpanAncestors200>({
|
||||
url: `/api/v1/traces/${traceID}/spans/${spanID}/ancestors`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListTraceSpanAncestorsQueryKey = (
|
||||
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
|
||||
params?: ListTraceSpanAncestorsParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/v1/traces/${traceID}/spans/${spanID}/ancestors`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getListTraceSpanAncestorsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanAncestors>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
|
||||
params?: ListTraceSpanAncestorsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ??
|
||||
getListTraceSpanAncestorsQueryKey({ traceID, spanID }, params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listTraceSpanAncestors>>
|
||||
> = ({ signal }) =>
|
||||
listTraceSpanAncestors({ traceID, spanID }, params, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled:
|
||||
traceID !== null &&
|
||||
traceID !== undefined &&
|
||||
spanID !== null &&
|
||||
spanID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListTraceSpanAncestorsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listTraceSpanAncestors>>
|
||||
>;
|
||||
export type ListTraceSpanAncestorsQueryError =
|
||||
ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List ancestors of a span
|
||||
*/
|
||||
|
||||
export function useListTraceSpanAncestors<
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanAncestors>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
|
||||
params?: ListTraceSpanAncestorsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanAncestors>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListTraceSpanAncestorsQueryOptions(
|
||||
{ traceID, spanID },
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List ancestors of a span
|
||||
*/
|
||||
export const invalidateListTraceSpanAncestors = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID, spanID }: ListTraceSpanAncestorsPathParameters,
|
||||
params?: ListTraceSpanAncestorsParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListTraceSpanAncestorsQueryKey({ traceID, spanID }, params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of the direct children of a span, one level below it and nothing deeper, in start order. It takes the same parameters as the span list. The list is empty for a span without children.
|
||||
* @summary List children of a span
|
||||
*/
|
||||
export const listTraceSpanChildren = (
|
||||
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
|
||||
params?: ListTraceSpanChildrenParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListTraceSpanChildren200>({
|
||||
url: `/api/v1/traces/${traceID}/spans/${spanID}/children`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListTraceSpanChildrenQueryKey = (
|
||||
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
|
||||
params?: ListTraceSpanChildrenParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/v1/traces/${traceID}/spans/${spanID}/children`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getListTraceSpanChildrenQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanChildren>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
|
||||
params?: ListTraceSpanChildrenParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanChildren>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ??
|
||||
getListTraceSpanChildrenQueryKey({ traceID, spanID }, params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listTraceSpanChildren>>
|
||||
> = ({ signal }) => listTraceSpanChildren({ traceID, spanID }, params, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled:
|
||||
traceID !== null &&
|
||||
traceID !== undefined &&
|
||||
spanID !== null &&
|
||||
spanID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanChildren>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListTraceSpanChildrenQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listTraceSpanChildren>>
|
||||
>;
|
||||
export type ListTraceSpanChildrenQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List children of a span
|
||||
*/
|
||||
|
||||
export function useListTraceSpanChildren<
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanChildren>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
|
||||
params?: ListTraceSpanChildrenParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanChildren>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListTraceSpanChildrenQueryOptions(
|
||||
{ traceID, spanID },
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List children of a span
|
||||
*/
|
||||
export const invalidateListTraceSpanChildren = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID, spanID }: ListTraceSpanChildrenPathParameters,
|
||||
params?: ListTraceSpanChildrenParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getListTraceSpanChildrenQueryKey({ traceID, spanID }, params) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a page of the spans below a span, at any depth, in tree order. It takes the same parameters as the span list, so view=error_origins returns the errors that started below the span.
|
||||
* @summary List descendants of a span
|
||||
*/
|
||||
export const listTraceSpanDescendants = (
|
||||
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
|
||||
params?: ListTraceSpanDescendantsParams,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<ListTraceSpanDescendants200>({
|
||||
url: `/api/v1/traces/${traceID}/spans/${spanID}/descendants`,
|
||||
method: 'GET',
|
||||
params,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getListTraceSpanDescendantsQueryKey = (
|
||||
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
|
||||
params?: ListTraceSpanDescendantsParams,
|
||||
) => {
|
||||
return [
|
||||
`/api/v1/traces/${traceID}/spans/${spanID}/descendants`,
|
||||
...(params ? [params] : []),
|
||||
] as const;
|
||||
};
|
||||
|
||||
export const getListTraceSpanDescendantsQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanDescendants>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
|
||||
params?: ListTraceSpanDescendantsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ??
|
||||
getListTraceSpanDescendantsQueryKey({ traceID, spanID }, params);
|
||||
|
||||
const queryFn: QueryFunction<
|
||||
Awaited<ReturnType<typeof listTraceSpanDescendants>>
|
||||
> = ({ signal }) =>
|
||||
listTraceSpanDescendants({ traceID, spanID }, params, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled:
|
||||
traceID !== null &&
|
||||
traceID !== undefined &&
|
||||
spanID !== null &&
|
||||
spanID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type ListTraceSpanDescendantsQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof listTraceSpanDescendants>>
|
||||
>;
|
||||
export type ListTraceSpanDescendantsQueryError =
|
||||
ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary List descendants of a span
|
||||
*/
|
||||
|
||||
export function useListTraceSpanDescendants<
|
||||
TData = Awaited<ReturnType<typeof listTraceSpanDescendants>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
|
||||
params?: ListTraceSpanDescendantsParams,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof listTraceSpanDescendants>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getListTraceSpanDescendantsQueryOptions(
|
||||
{ traceID, spanID },
|
||||
params,
|
||||
options,
|
||||
);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary List descendants of a span
|
||||
*/
|
||||
export const invalidateListTraceSpanDescendants = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID, spanID }: ListTraceSpanDescendantsPathParameters,
|
||||
params?: ListTraceSpanDescendantsParams,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{
|
||||
queryKey: getListTraceSpanDescendantsQueryKey({ traceID, spanID }, params),
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the totals of a trace and no spans: its time range, root span, span and error counts, and whether any spans are missing. AI traces also include model and tool call counts, and token and cost totals. For the spans to look at, use the trace highlights.
|
||||
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
|
||||
* @summary Get summary for a trace
|
||||
*/
|
||||
export const getTraceSummary = (
|
||||
|
||||
@@ -21,6 +21,7 @@ import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
convertBuilderQueriesToV5,
|
||||
createAggregation,
|
||||
mapPanelTypeToRequestType,
|
||||
prepareQueryRangePayloadV5,
|
||||
} from './prepareQueryRangePayloadV5';
|
||||
@@ -1015,3 +1016,47 @@ describe('convertBuilderQueriesToV5 builder query type', () => {
|
||||
expect(buildEnvelope(builderQueryType, 'trace').type).toBe('builder_query');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAggregation fallback', () => {
|
||||
const logsQuery = (expression: string): Partial<IBuilderQuery> => ({
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
it('sends no aggregation for a heatmap with no field', () => {
|
||||
expect(createAggregation(logsQuery(''), PANEL_TYPES.HEATMAP)).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a field on a heatmap and turns it into count() elsewhere', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.HEATMAP),
|
||||
).toStrictEqual([{ expression: 'duration_nano' }]);
|
||||
expect(
|
||||
createAggregation(logsQuery('duration_nano'), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('still defaults other panels to count()', () => {
|
||||
expect(
|
||||
createAggregation(logsQuery(''), PANEL_TYPES.TIME_SERIES),
|
||||
).toStrictEqual([{ expression: 'count()' }]);
|
||||
});
|
||||
|
||||
it('sends the field of a logs heatmap query', () => {
|
||||
const [envelope] = convertBuilderQueriesToV5(
|
||||
{
|
||||
A: {
|
||||
...logsQuery('duration_nano'),
|
||||
queryName: 'A',
|
||||
} as IBuilderQuery,
|
||||
},
|
||||
mapPanelTypeToRequestType(PANEL_TYPES.HEATMAP),
|
||||
PANEL_TYPES.HEATMAP,
|
||||
);
|
||||
expect((envelope.spec as LogBuilderQuery).aggregations).toStrictEqual([
|
||||
{ expression: 'duration_nano' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { parseAggregations } from 'lib/query/aggregationExpression';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import { DynamicVariableSuggestion } from 'providers/Dashboard/store/dynamicVariableSuggestions';
|
||||
@@ -240,32 +242,6 @@ function createBaseSpec(
|
||||
};
|
||||
}
|
||||
|
||||
// Utility to parse aggregation expressions with optional alias
|
||||
export function parseAggregations(
|
||||
expression: string,
|
||||
availableAlias?: string,
|
||||
): { expression: string; alias?: string }[] {
|
||||
const result: { expression: string; alias?: string }[] = [];
|
||||
// Matches function calls like "count()" or "sum(field)" with optional alias like "as 'alias'"
|
||||
// Handles quoted ('alias'), dash-separated (field-name), and unquoted values after "as" keyword
|
||||
const regex =
|
||||
/([a-zA-Z0-9_]+\([^)]*\))(?:\s*as\s+((?:'[^']*'|"[^"]*"|[a-zA-Z0-9_-]+)))?/g;
|
||||
let match = regex.exec(expression);
|
||||
while (match !== null) {
|
||||
const expr = match[1];
|
||||
let alias = match[2] || availableAlias; // Use provided alias or availableAlias if not matched
|
||||
if (alias) {
|
||||
// Remove quotes if present
|
||||
alias = alias.replace(/^['"]|['"]$/g, '');
|
||||
result.push({ expression: expr, alias });
|
||||
} else {
|
||||
result.push({ expression: expr });
|
||||
}
|
||||
match = regex.exec(expression);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createAggregation(
|
||||
queryData: any,
|
||||
panelType?: PANEL_TYPES,
|
||||
@@ -310,18 +286,28 @@ export function createAggregation(
|
||||
];
|
||||
}
|
||||
|
||||
// A heatmap buckets the field the user names; count() would be rejected as one.
|
||||
// Elsewhere a field is not an aggregation, so it falls back to count().
|
||||
const isDistributionField = aggregatesDistributionField(
|
||||
panelType,
|
||||
queryData.dataSource,
|
||||
);
|
||||
const fallback = isDistributionField ? [] : [{ expression: 'count()' }];
|
||||
|
||||
if (queryData.aggregations?.length > 0) {
|
||||
return queryData.aggregations.flatMap(
|
||||
(agg: { expression: string; alias?: string }) => {
|
||||
const parsedAggregations = parseAggregations(agg.expression, agg?.alias);
|
||||
return isEmpty(parsedAggregations)
|
||||
? [{ expression: 'count()' }]
|
||||
: parsedAggregations;
|
||||
const parsedAggregations = parseAggregations(
|
||||
agg.expression,
|
||||
agg?.alias,
|
||||
isDistributionField,
|
||||
);
|
||||
return isEmpty(parsedAggregations) ? fallback : parsedAggregations;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return [{ expression: 'count()' }];
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
1
frontend/src/auto-import-registry.d.ts
vendored
1
frontend/src/auto-import-registry.d.ts
vendored
@@ -12,4 +12,5 @@
|
||||
|
||||
import '@signozhq/design-tokens';
|
||||
import '@signozhq/icons';
|
||||
import '@signozhq/noz-client';
|
||||
import '@signozhq/ui';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
|
||||
import LabelColumn from './LabelColumn';
|
||||
|
||||
@@ -92,7 +92,9 @@ describe('LabelColumn', () => {
|
||||
renderWithProviders(<LabelColumn labels={labels} />);
|
||||
|
||||
const isHidden = (label: string): boolean =>
|
||||
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
|
||||
screen
|
||||
.getByTestId(`label-tag-container-${label}`)
|
||||
.classList.contains('overflowed');
|
||||
|
||||
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
|
||||
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
|
||||
@@ -157,8 +159,7 @@ describe('LabelColumn', () => {
|
||||
it('should render empty when no labels provided', () => {
|
||||
renderWithProviders(<LabelColumn labels={[]} />);
|
||||
|
||||
const column = screen.getByTestId('label-column');
|
||||
expect(column.children).toHaveLength(0);
|
||||
expect(screen.getByTestId('label-column')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('should use primary color by default', () => {
|
||||
|
||||
@@ -45,7 +45,7 @@ function LabelTag({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<span className={className}>
|
||||
<span className={className} data-testid={`label-tag-container-${label}`}>
|
||||
<Badge
|
||||
textTransform="none"
|
||||
color={color ?? 'secondary'}
|
||||
|
||||
@@ -22,7 +22,10 @@ function AppLoading(): JSX.Element {
|
||||
const isDarkMode = getThemeFromStorage();
|
||||
|
||||
return (
|
||||
<div className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}>
|
||||
<div
|
||||
className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}
|
||||
data-testid="app-loading-container"
|
||||
>
|
||||
<div className="perilin-bg" />
|
||||
<div className="app-loading-content">
|
||||
<div className="brand">
|
||||
@@ -53,7 +56,7 @@ function AppLoading(): JSX.Element {
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="loader" />
|
||||
<div className="loader" data-testid="app-loading-loader" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { screen } from 'tests/test-utils';
|
||||
|
||||
import getLocal from '../../../api/browser/localstorage/get';
|
||||
import AppLoading from '../AppLoading';
|
||||
@@ -15,7 +16,6 @@ describe('AppLoading', () => {
|
||||
const SIGNOZ_TEXT = 'SigNoz';
|
||||
const TAGLINE_TEXT =
|
||||
'OpenTelemetry-Native Logs, Metrics and Traces in a single pane';
|
||||
const CONTAINER_SELECTOR = '.app-loading-container';
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -33,7 +33,7 @@ describe('AppLoading', () => {
|
||||
expect(screen.getByText(TAGLINE_TEXT)).toBeInTheDocument();
|
||||
|
||||
// Check if dark theme class is applied
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
expect(container).not.toHaveClass('lightMode');
|
||||
});
|
||||
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
|
||||
expect(tagline).toBeInTheDocument();
|
||||
|
||||
// Check for loader
|
||||
const loader = document.querySelector('.loader');
|
||||
const loader = screen.getByTestId('app-loading-loader');
|
||||
expect(loader).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -72,7 +72,7 @@ describe('AppLoading', () => {
|
||||
|
||||
// Should still render with dark theme as fallback
|
||||
expect(screen.getByText(SIGNOZ_TEXT)).toBeInTheDocument();
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('submit button becomes disabled after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -86,7 +86,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('successful submit shows toast.success and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -112,7 +112,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('pressing Enter again while creating sends one request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requests = 0;
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -146,7 +146,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows toast.error on API error and keeps modal open', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -186,7 +186,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('Cancel button closes modal without submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const cancelBtn = await screen.findByTestId('create-sa-cancel-btn');
|
||||
@@ -217,7 +217,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('keeps the footer usable when create permission is denied', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderModal();
|
||||
@@ -242,7 +242,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows "Name is required" after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
|
||||
@@ -5,7 +5,7 @@ import dayjs from 'dayjs';
|
||||
import { Calendar as CalendarIcon, Check, X } from '@signozhq/icons';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
import { DateRange } from './CustomTimePickerPopoverContent';
|
||||
import type { DateRange } from './CustomTimePickerPopoverContent';
|
||||
|
||||
function CalendarContainer({
|
||||
dateRange,
|
||||
@@ -50,7 +50,7 @@ function CalendarContainer({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="calendar-container">
|
||||
<div className="calendar-container" data-testid="calendar-container">
|
||||
<div className="calendar-container-header">
|
||||
<CalendarIcon size={12} />
|
||||
<div className="calendar-container-header-title">
|
||||
@@ -80,6 +80,7 @@ function CalendarContainer({
|
||||
<Button
|
||||
type="primary"
|
||||
className="periscope-btn secondary cancel-btn"
|
||||
data-testid="calendar-cancel-btn"
|
||||
onClick={onCancel}
|
||||
icon={<X size={12} />}
|
||||
>
|
||||
@@ -88,6 +89,7 @@ function CalendarContainer({
|
||||
<Button
|
||||
type="primary"
|
||||
className="periscope-btn primary apply-btn"
|
||||
data-testid="calendar-apply-btn"
|
||||
onClick={onApply}
|
||||
icon={<Check size={12} />}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.calendarContainerFallback {
|
||||
justify-content: center;
|
||||
// Header, caption, weekday row and actions take 160px; each week row 40px.
|
||||
min-height: calc(160px + var(--calendar-week-count) * 40px);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { CSSProperties } from 'react';
|
||||
import { Spinner } from '@signozhq/ui/spinner';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { getCalendarWeekCount } from './calendarUtils';
|
||||
|
||||
import styles from './CalendarContainerFallback.module.scss';
|
||||
|
||||
function CalendarContainerFallback({
|
||||
month,
|
||||
}: {
|
||||
month: Date | undefined;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={cx('calendar-container', styles.calendarContainerFallback)}
|
||||
style={
|
||||
{ '--calendar-week-count': getCalendarWeekCount(month) } as CSSProperties
|
||||
}
|
||||
data-testid="calendar-container-fallback"
|
||||
aria-busy="true"
|
||||
>
|
||||
<Spinner size={20} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CalendarContainerFallback;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { fireEvent, screen, userEvent } from 'tests/test-utils';
|
||||
import dayjs from 'dayjs';
|
||||
import { mockAppLocation } from 'tests/router-mocks';
|
||||
import * as timeUtils from 'utils/timeUtils';
|
||||
@@ -157,7 +158,8 @@ describe('CustomTimePicker', () => {
|
||||
expect(onValid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats close after change like pressing Enter (blur + chevron)', () => {
|
||||
it('treats close after change like pressing Enter (blur + chevron)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onValid = jest.fn();
|
||||
const onError = jest.fn();
|
||||
|
||||
@@ -166,16 +168,13 @@ describe('CustomTimePicker', () => {
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Open and change value so "changed since open" is true
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: '5m' } });
|
||||
fireEvent.blur(input);
|
||||
await user.click(input);
|
||||
await user.clear(input);
|
||||
await user.type(input, '5m');
|
||||
await user.tab();
|
||||
|
||||
// Click the chevron (which triggers handleClose)
|
||||
const chevron = document.querySelector(
|
||||
'.time-input-suffix-icon-badge',
|
||||
) as HTMLElement;
|
||||
|
||||
fireEvent.click(chevron);
|
||||
await user.click(screen.getByTestId('time-picker-close-chevron'));
|
||||
|
||||
// Should have applied the value (same as Enter)
|
||||
expect(onValid).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -640,12 +640,14 @@ function CustomTimePicker({
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleClose}
|
||||
data-testid="time-picker-close-chevron"
|
||||
/>
|
||||
) : (
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleOpen}
|
||||
data-testid="time-picker-open-chevron"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
Dispatch,
|
||||
lazy,
|
||||
SetStateAction,
|
||||
Suspense,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
@@ -24,15 +26,20 @@ import dayjs from 'dayjs';
|
||||
import { Clock, PenLine, TriangleAlert } from '@signozhq/icons';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { getCustomTimeRanges } from 'utils/customTimeRangeUtils';
|
||||
import { lazyRetry } from 'utils/lazyWithRetries';
|
||||
import { TimeRangeValidationResult } from 'utils/timeUtils';
|
||||
|
||||
import CalendarContainer from './CalendarContainer';
|
||||
import CalendarContainerFallback from './CalendarContainerFallback';
|
||||
import { CustomTimePickerInputStatus } from './CustomTimePicker';
|
||||
import TimezonePicker from './TimezonePicker';
|
||||
import { Timezone } from './timezoneUtils';
|
||||
|
||||
import './CustomTimePicker.styles.scss';
|
||||
|
||||
const CalendarContainer = lazy(() =>
|
||||
lazyRetry(() => import('./CalendarContainer')),
|
||||
);
|
||||
|
||||
const TO_MILLISECONDS_FACTOR = 1000_000;
|
||||
|
||||
export type DateRange = {
|
||||
@@ -291,12 +298,16 @@ function CustomTimePickerPopoverContent({
|
||||
)}
|
||||
>
|
||||
{customDateTimeVisible ? (
|
||||
<CalendarContainer
|
||||
dateRange={dateRange}
|
||||
onSelectDateRange={handleSelectDateRange}
|
||||
onCancel={handleCalendarRangeCancel}
|
||||
onApply={handleCalendarRangeApply}
|
||||
/>
|
||||
<Suspense
|
||||
fallback={<CalendarContainerFallback month={dateRange?.from} />}
|
||||
>
|
||||
<CalendarContainer
|
||||
dateRange={dateRange}
|
||||
onSelectDateRange={handleSelectDateRange}
|
||||
onCancel={handleCalendarRangeCancel}
|
||||
onApply={handleCalendarRangeApply}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<div className="time-selector-container">
|
||||
{customDateTimeInputStatus === CustomTimePickerInputStatus.ERROR &&
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import CustomTimePickerPopoverContent from '../CustomTimePickerPopoverContent';
|
||||
import { CustomTimePickerInputStatus } from '../CustomTimePicker';
|
||||
|
||||
const NANOSECONDS_PER_MILLISECOND = 1_000_000;
|
||||
|
||||
const minTime =
|
||||
dayjs('2024-01-01 00:00:00').valueOf() * NANOSECONDS_PER_MILLISECOND;
|
||||
const maxTime =
|
||||
dayjs('2024-01-03 00:00:00').valueOf() * NANOSECONDS_PER_MILLISECOND;
|
||||
|
||||
interface RenderOptions {
|
||||
customDateTimeVisible: boolean;
|
||||
setIsOpen?: jest.Mock;
|
||||
setCustomDTPickerVisible?: jest.Mock;
|
||||
onCustomDateHandler?: jest.Mock;
|
||||
}
|
||||
|
||||
function renderPopoverContent({
|
||||
customDateTimeVisible,
|
||||
setIsOpen = jest.fn(),
|
||||
setCustomDTPickerVisible = jest.fn(),
|
||||
onCustomDateHandler = jest.fn(),
|
||||
}: RenderOptions): void {
|
||||
render(
|
||||
<CustomTimePickerPopoverContent
|
||||
isLiveLogsEnabled={false}
|
||||
minTime={minTime}
|
||||
maxTime={maxTime}
|
||||
options={[
|
||||
{ label: 'Last 5 minutes', value: '5m' },
|
||||
{ label: 'Custom Date Range', value: 'custom' },
|
||||
]}
|
||||
setIsOpen={setIsOpen}
|
||||
customDateTimeVisible={customDateTimeVisible}
|
||||
setCustomDTPickerVisible={setCustomDTPickerVisible}
|
||||
onCustomDateHandler={onCustomDateHandler}
|
||||
onSelectHandler={jest.fn()}
|
||||
onTimezoneChange={jest.fn()}
|
||||
onGoLive={jest.fn()}
|
||||
selectedTime="custom"
|
||||
activeView="datetime"
|
||||
setActiveView={jest.fn()}
|
||||
isOpenedFromFooter={false}
|
||||
setIsOpenedFromFooter={jest.fn()}
|
||||
onExitLiveLogs={jest.fn()}
|
||||
showRecentlyUsed={false}
|
||||
customDateTimeInputStatus={CustomTimePickerInputStatus.UNSET}
|
||||
inputErrorDetails={null}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('CustomTimePickerPopoverContent calendar', () => {
|
||||
it('keeps the calendar out of the popover while relative times show', () => {
|
||||
renderPopoverContent({ customDateTimeVisible: false });
|
||||
|
||||
expect(screen.getByTestId('time-option-5m')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('calendar-container-fallback'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('calendar-container')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('holds the calendar slot with a fallback until the calendar loads', async () => {
|
||||
renderPopoverContent({ customDateTimeVisible: true });
|
||||
|
||||
expect(
|
||||
screen
|
||||
.getByTestId('calendar-container-fallback')
|
||||
.style.getPropertyValue('--calendar-week-count'),
|
||||
).toBe('5');
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('calendar-container'),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('calendar-container-fallback'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes the calendar view when Cancel is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const setCustomDTPickerVisible = jest.fn();
|
||||
renderPopoverContent({
|
||||
customDateTimeVisible: true,
|
||||
setCustomDTPickerVisible,
|
||||
});
|
||||
|
||||
await user.click(await screen.findByTestId('calendar-cancel-btn'));
|
||||
|
||||
expect(setCustomDTPickerVisible).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('applies the selected range and closes the popover when Apply is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const setIsOpen = jest.fn();
|
||||
const onCustomDateHandler = jest.fn();
|
||||
renderPopoverContent({
|
||||
customDateTimeVisible: true,
|
||||
setIsOpen,
|
||||
onCustomDateHandler,
|
||||
});
|
||||
|
||||
await user.click(await screen.findByTestId('calendar-apply-btn'));
|
||||
|
||||
expect(onCustomDateHandler).toHaveBeenCalledTimes(1);
|
||||
const [[from, to]] = onCustomDateHandler.mock.calls[0];
|
||||
expect(to.diff(from, 'hour')).toBe(71);
|
||||
expect(setIsOpen).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('applies a range picked on the calendar', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onCustomDateHandler = jest.fn();
|
||||
renderPopoverContent({ customDateTimeVisible: true, onCustomDateHandler });
|
||||
|
||||
const calendar = await screen.findByTestId('calendar-container');
|
||||
await user.click(
|
||||
within(calendar).getByRole('button', { name: /January 12th, 2024/ }),
|
||||
);
|
||||
await user.click(
|
||||
within(calendar).getByRole('button', { name: /January 10th, 2024/ }),
|
||||
);
|
||||
await user.click(screen.getByTestId('calendar-apply-btn'));
|
||||
|
||||
expect(onCustomDateHandler).toHaveBeenCalledTimes(1);
|
||||
const [[from, to]] = onCustomDateHandler.mock.calls[0];
|
||||
expect(from.format('YYYY-MM-DD HH:mm')).toBe('2024-01-10 00:00');
|
||||
expect(to.format('YYYY-MM-DD HH:mm')).toBe('2024-01-12 23:59');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getCalendarWeekCount } from '../calendarUtils';
|
||||
|
||||
describe('getCalendarWeekCount', () => {
|
||||
it.each([
|
||||
['February 2026', new Date(2026, 1, 14), 4],
|
||||
['January 2024', new Date(2024, 0, 31), 5],
|
||||
['June 2024', new Date(2024, 5, 1), 6],
|
||||
])('counts the week rows of %s', (_month, date, weeks) => {
|
||||
expect(getCalendarWeekCount(date)).toBe(weeks);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
/** Week rows the calendar renders for `month`, with weeks starting on Sunday. */
|
||||
export function getCalendarWeekCount(month: Date | undefined): number {
|
||||
const firstDay = dayjs(month).startOf('month');
|
||||
|
||||
return Math.ceil((firstDay.day() + firstDay.daysInMonth()) / 7);
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import dayjs from 'dayjs';
|
||||
import { screen, userEvent } from 'storybook/test';
|
||||
|
||||
import { withCanvas } from '@/storybook/decorators/withCanvas';
|
||||
|
||||
import CustomTimePicker from '../CustomTimePicker';
|
||||
import {
|
||||
openCustomRangeCalendar,
|
||||
openRelativeTimes,
|
||||
openTimezoneMenu,
|
||||
} from './__story_mockdata__/customTimePicker.play';
|
||||
|
||||
const minTime = dayjs('2025-01-15T11:00:00Z').valueOf() * 1_000_000;
|
||||
const maxTime = dayjs('2025-01-15T12:00:00Z').valueOf() * 1_000_000;
|
||||
@@ -13,9 +17,11 @@ const maxTime = dayjs('2025-01-15T12:00:00Z').valueOf() * 1_000_000;
|
||||
function TimePickerFixture(): JSX.Element {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedTime, setSelectedTime] = useState('1h');
|
||||
const [customDTPickerVisible, setCustomDTPickerVisible] = useState(false);
|
||||
|
||||
return (
|
||||
<CustomTimePicker
|
||||
customDateTimeVisible={customDTPickerVisible}
|
||||
isModalTimeSelection
|
||||
items={[
|
||||
{ label: 'Last 15 minutes', value: '15m' },
|
||||
@@ -33,6 +39,7 @@ function TimePickerFixture(): JSX.Element {
|
||||
onValidCustomDateChange={(): void => undefined}
|
||||
selectedTime={selectedTime}
|
||||
selectedValue="15 Jan 2025 11:00:00 - 15 Jan 2025 12:00:00"
|
||||
setCustomDTPickerVisible={setCustomDTPickerVisible}
|
||||
setOpen={setOpen}
|
||||
/>
|
||||
);
|
||||
@@ -51,19 +58,15 @@ type Story = StoryObj<typeof meta>;
|
||||
|
||||
/** Interaction: the time-range menu is open with its relative-range choices. */
|
||||
export const TimeRangeMenuOpen: Story = {
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.click(await screen.findByRole('textbox'));
|
||||
await screen.findByText('RELATIVE TIMES');
|
||||
},
|
||||
play: openRelativeTimes,
|
||||
};
|
||||
|
||||
/** Interaction: the timezone menu is reached through the real time-range footer. */
|
||||
export const TimezoneMenuOpen: Story = {
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.click(await screen.findByRole('textbox'));
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Change Timezone' }),
|
||||
);
|
||||
await screen.findByPlaceholderText('Search timezones...');
|
||||
},
|
||||
play: openTimezoneMenu,
|
||||
};
|
||||
|
||||
/** Interaction: Custom opens the range calendar on the current day range. */
|
||||
export const CustomRangeCalendarOpen: Story = {
|
||||
play: openCustomRangeCalendar,
|
||||
};
|
||||
|
||||
39
frontend/src/components/CustomTimePicker/stories/__story_mockdata__/customTimePicker.play.ts
generated
Normal file
39
frontend/src/components/CustomTimePicker/stories/__story_mockdata__/customTimePicker.play.ts
generated
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
|
||||
* Do not hand-edit: regenerate instead.
|
||||
*/
|
||||
|
||||
import { expect, screen, userEvent, within } from 'storybook/test';
|
||||
|
||||
const openTimeRangeMenu = async (): Promise<void> => {
|
||||
await userEvent.click(await screen.findByRole('textbox'));
|
||||
await screen.findByTestId('time-option-custom');
|
||||
};
|
||||
|
||||
export const openRelativeTimes = async (): Promise<void> => {
|
||||
await openTimeRangeMenu();
|
||||
await screen.findByText('RELATIVE TIMES');
|
||||
};
|
||||
|
||||
export const openTimezoneMenu = async (): Promise<void> => {
|
||||
await openTimeRangeMenu();
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Change Timezone' }),
|
||||
);
|
||||
await screen.findByPlaceholderText('Search timezones...');
|
||||
};
|
||||
|
||||
/** The calendar loads in its own chunk, so it is awaited past the fallback. */
|
||||
export const openCustomRangeCalendar = async (): Promise<void> => {
|
||||
await openTimeRangeMenu();
|
||||
await userEvent.click(screen.getByTestId('time-option-custom'));
|
||||
|
||||
const calendar = await screen.findByTestId(
|
||||
'calendar-container',
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await expect(
|
||||
within(calendar).getByTestId('calendar-apply-btn'),
|
||||
).toBeInTheDocument();
|
||||
};
|
||||
@@ -176,6 +176,7 @@ export default function DownloadOptionsMenu({
|
||||
arrow={false}
|
||||
open={isPopoverOpen}
|
||||
onOpenChange={setIsPopoverOpen}
|
||||
destroyTooltipOnHide
|
||||
rootClassName="download-popover"
|
||||
>
|
||||
<Tooltip title="Download" placement="top">
|
||||
|
||||
@@ -273,7 +273,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('enables Save after editing name and calls updateUser on confirm', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
@@ -306,7 +306,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('does not close the drawer after a successful save', async () => {
|
||||
const onClose = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
|
||||
@@ -331,7 +331,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('adding a new role creates a user role without removing existing ones', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockSet = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useCreateUserRole as jest.Mock).mockReturnValue({
|
||||
@@ -365,7 +365,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('deselecting a role deletes the user role by its assignment id', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
@@ -392,7 +392,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('shows delete confirm dialog and calls deleteUser for active members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -553,7 +553,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls deleteUser after confirming revoke invite for invited members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -583,7 +583,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls updateUser when saving name change for an invited member', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useGetUser as jest.Mock).mockReturnValue({
|
||||
@@ -641,7 +641,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows SaveErrorItem when updateUser fails for name change', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
mutateAsync: jest.fn().mockRejectedValue(new Error('server error')),
|
||||
@@ -669,7 +669,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for active member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -700,7 +700,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for invited member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -740,7 +740,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (isSelf)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -771,7 +771,11 @@ describe('EditMemberDrawer', () => {
|
||||
it('keeps roles editable', async () => {
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await expect(screen.findByText('Select roles')).resolves.toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByTestId(
|
||||
`member-roles-select-chip-${managedRoles[0].id}-remove`,
|
||||
),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('member-roles-locked')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -807,7 +811,7 @@ describe('EditMemberDrawer', () => {
|
||||
isLoading: false,
|
||||
});
|
||||
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
const input = await screen.findByDisplayValue('Alice Smith');
|
||||
@@ -871,7 +875,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -882,7 +886,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not call createResetPasswordToken when Reset Link is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(
|
||||
@@ -899,7 +903,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('calls POST and opens the reset link dialog with the generated link and expiry', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -921,7 +925,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
|
||||
|
||||
// Click the close button
|
||||
const closeButton = screen.getByTestId('close-button');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(closeButton);
|
||||
|
||||
// Check if onClose was called
|
||||
@@ -145,7 +145,7 @@ it('should open the modal when the trigger component is clicked', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('Open Error Modal');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
// Check if the modal is displayed
|
||||
@@ -165,12 +165,13 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('error');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('An error occurred')).toBeInTheDocument();
|
||||
});
|
||||
const modal = screen.getByRole('dialog');
|
||||
|
||||
// Trigger the onCancel event
|
||||
await user.click(screen.getByTestId('close-button'));
|
||||
@@ -180,8 +181,6 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// check if the modal is not visible
|
||||
const modal = document.getElementsByClassName('ant-modal');
|
||||
const style = window.getComputedStyle(modal[0]);
|
||||
expect(style.display).toBe('none');
|
||||
expect(modal).toHaveStyle({ display: 'none' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider } from 'react-redux';
|
||||
import { act, render, renderHook } from '@testing-library/react';
|
||||
import { act, render, renderHook } from 'tests/test-utils';
|
||||
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
|
||||
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
|
||||
import { useGlobalTimeStore } from 'store/globalTime/globalTimeStore';
|
||||
@@ -42,13 +42,13 @@ describe('GlobalTimeStoreAdapter', () => {
|
||||
globalTime: createGlobalTimeState(),
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<Provider store={store}>
|
||||
<GlobalTimeStoreAdapter />
|
||||
</Provider>,
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(asFragment().hasChildNodes()).toBe(false);
|
||||
});
|
||||
|
||||
it('should sync relative time from Redux to Zustand store', () => {
|
||||
|
||||
@@ -2,8 +2,14 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
function AnnouncementsModal(): JSX.Element {
|
||||
return (
|
||||
<div className="announcements-modal-container">
|
||||
<div className="announcements-modal-container-header">
|
||||
<div
|
||||
className="announcements-modal-container"
|
||||
data-testid="announcements-modal"
|
||||
>
|
||||
<div
|
||||
className="announcements-modal-container-header"
|
||||
data-testid="announcements-modal-header"
|
||||
>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import AnnouncementsModal from '../AnnouncementsModal';
|
||||
|
||||
@@ -12,15 +12,14 @@ describe('AnnouncementsModal', () => {
|
||||
it('should have proper structure and classes', () => {
|
||||
render(<AnnouncementsModal />);
|
||||
|
||||
const container = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container');
|
||||
expect(container).toBeInTheDocument();
|
||||
const container = screen.getByTestId('announcements-modal');
|
||||
expect(container).toHaveClass('announcements-modal-container');
|
||||
|
||||
const headerContainer = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container-header');
|
||||
expect(headerContainer).toBeInTheDocument();
|
||||
const headerContainer = within(container).getByTestId(
|
||||
'announcements-modal-header',
|
||||
);
|
||||
expect(headerContainer).toHaveClass('announcements-modal-container-header');
|
||||
expect(headerContainer).toHaveTextContent('Announcements');
|
||||
});
|
||||
|
||||
it('should render without any errors', () => {
|
||||
|
||||
@@ -64,7 +64,10 @@ function InviteMembers({
|
||||
const hasSuccesses = successResults.length > 0;
|
||||
|
||||
return (
|
||||
<div className={cx(styles.inviteMembers, className)}>
|
||||
<div
|
||||
className={cx(styles.inviteMembers, className)}
|
||||
data-testid="invite-members"
|
||||
>
|
||||
<div className={styles.table}>
|
||||
{showHeader && (
|
||||
<div className={styles.header}>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import InviteMembers from '../InviteMembers';
|
||||
import { InviteMembersProps } from '../types';
|
||||
|
||||
import { pickRole } from './roleSelectUtils';
|
||||
import {
|
||||
@@ -9,9 +10,12 @@ import {
|
||||
createErrorHandler,
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
enterInviteEmail,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
|
||||
|
||||
describe('InviteMembers - Edge Cases', () => {
|
||||
beforeEach(() => {
|
||||
server.use(createRolesHandler(), createSuccessHandler());
|
||||
@@ -23,7 +27,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('reset behavior', () => {
|
||||
it('clears all rows when reset is called', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -36,13 +40,12 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
|
||||
await user.click(screen.getByTestId('reset-btn'));
|
||||
|
||||
const resetInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
const resetInputs = screen.getAllByTestId(/^invite-email-.*-field$/);
|
||||
expect(resetInputs).toHaveLength(2);
|
||||
resetInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
@@ -50,7 +53,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears results on reset', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -67,8 +70,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -84,7 +86,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('results cleared on edit', () => {
|
||||
it('clears API error when email is edited', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -98,8 +100,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -107,7 +108,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
screen.findByTestId('invite-api-error'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.type(emailInputs[0], 'x');
|
||||
await user.type(screen.getAllByTestId(/^invite-email-.*-field$/)[0], 'x');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId('invite-api-error')).not.toBeInTheDocument();
|
||||
@@ -115,7 +116,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
});
|
||||
|
||||
it('clears API error when role is changed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -129,8 +130,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -148,8 +148,8 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('empty submission', () => {
|
||||
it('does not submit when no rows are touched', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSuccess = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -170,7 +170,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('submitting state', () => {
|
||||
it('disables submit while submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -182,8 +182,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
const submitBtn = screen.getByTestId('submit-btn');
|
||||
@@ -197,7 +196,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
|
||||
describe('whitespace handling', () => {
|
||||
it('trims email whitespace before submission', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const calls: { email: string }[] = [];
|
||||
|
||||
server.use(
|
||||
@@ -218,8 +217,7 @@ describe('InviteMembers - Edge Cases', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], ' alice@signoz.io ');
|
||||
await enterInviteEmail(user, 0, ' alice@signoz.io ');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
@@ -66,9 +66,9 @@ describe('InviteMembers - Rendering', () => {
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<InviteMembers className="custom-class" />);
|
||||
render(<InviteMembers className="custom-class" />);
|
||||
|
||||
expect(container.querySelector('.custom-class')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-members')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('renders footer via renderFooter prop', () => {
|
||||
|
||||
@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('adds a row when "Add another" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('removes a row when trash button is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('respects minRows constraint when removing rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} minRows={2} />);
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('cannot remove rows below minRows=1 default', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('preserves data in other rows when removing one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import InviteMembers from '../InviteMembers';
|
||||
import { InviteMembersProps } from '../types';
|
||||
|
||||
import { pickRole } from './roleSelectUtils';
|
||||
import {
|
||||
@@ -10,9 +11,12 @@ import {
|
||||
createRolesHandler,
|
||||
createSuccessHandler,
|
||||
createTrackingHandler,
|
||||
enterInviteEmail,
|
||||
VALID_EMAIL,
|
||||
} from './testUtils';
|
||||
|
||||
type InviteCallback = Required<InviteMembersProps>['onSuccess'];
|
||||
|
||||
describe('InviteMembers - Submission', () => {
|
||||
beforeEach(() => {
|
||||
server.use(createRolesHandler(), createSuccessHandler());
|
||||
@@ -24,7 +28,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('API calls', () => {
|
||||
it('calls createUser API for each touched row', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -39,8 +43,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -55,7 +58,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls createUser API for multiple touched rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const { handler, calls } = createTrackingHandler();
|
||||
server.use(handler);
|
||||
|
||||
@@ -70,15 +73,11 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
|
||||
await user.type(emailInputs[2], 'charlie@signoz.io');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickRole(user, 2, 'role-admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -104,8 +103,8 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('callbacks', () => {
|
||||
it('calls onSuccess when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onSuccess = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -118,8 +117,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -130,8 +128,8 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onAllFailed when all invites fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onAllFailed = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -146,8 +144,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -166,10 +163,10 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('calls onPartialSuccess when some invites succeed and some fail', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onPartialSuccess = jest.fn();
|
||||
const onSuccess = jest.fn();
|
||||
const onAllFailed = jest.fn();
|
||||
const user = userEvent.setup();
|
||||
const onPartialSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const onSuccess = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const onAllFailed = jest.fn() as jest.MockedFunction<InviteCallback>;
|
||||
const apiCalls: string[] = [];
|
||||
let callCount = 0;
|
||||
|
||||
@@ -208,12 +205,9 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
|
||||
await user.type(emailInputs[0], 'alice@signoz.io');
|
||||
await enterInviteEmail(user, 0, 'alice@signoz.io');
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.type(emailInputs[1], 'bob@signoz.io');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -252,7 +246,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('result display', () => {
|
||||
it('shows success callout when all invites succeed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -264,8 +258,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -276,7 +269,7 @@ describe('InviteMembers - Submission', () => {
|
||||
});
|
||||
|
||||
it('shows error callout with failed emails when API fails', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(createErrorHandler('already_exists', 'User already exists'));
|
||||
|
||||
@@ -290,8 +283,7 @@ describe('InviteMembers - Submission', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
@@ -305,7 +297,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
describe('footer props', () => {
|
||||
it('provides correct canSubmit state', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -319,14 +311,13 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).toBeDisabled();
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], VALID_EMAIL);
|
||||
await enterInviteEmail(user, 0, VALID_EMAIL);
|
||||
|
||||
expect(screen.getByTestId('submit-btn')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('provides touchedCount', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -339,12 +330,11 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('0');
|
||||
|
||||
const emailInputs = screen.getAllByPlaceholderText('e.g. john@signoz.io');
|
||||
await user.type(emailInputs[0], 'a@b.com');
|
||||
await enterInviteEmail(user, 0, 'a@b.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('1');
|
||||
|
||||
await user.type(emailInputs[1], 'c@d.com');
|
||||
await enterInviteEmail(user, 1, 'c@d.com');
|
||||
|
||||
expect(screen.getByTestId('touched-count')).toHaveTextContent('2');
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('email validation', () => {
|
||||
it('shows email validation error when email is invalid and role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('shows inline error for invalid email field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears validation error when email is corrected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -104,7 +104,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('role validation', () => {
|
||||
it('shows role validation error when role is missing', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears role validation error when role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -159,7 +159,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('combined validation', () => {
|
||||
it('shows combined error when both email and role are invalid', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -186,7 +186,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('touched rows', () => {
|
||||
it('only validates touched rows (rows with email or role)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { RestHandler } from 'msw';
|
||||
import { rest } from 'mocks-server/server';
|
||||
import { screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>;
|
||||
|
||||
export const CREATE_USER_ENDPOINT = '*/api/v2/users';
|
||||
export const LIST_ROLES_ENDPOINT = '*/api/v1/roles';
|
||||
@@ -52,3 +55,12 @@ export function createTrackingHandler(): {
|
||||
});
|
||||
return { handler, calls };
|
||||
}
|
||||
|
||||
export async function enterInviteEmail(
|
||||
user: User,
|
||||
rowIndex: number,
|
||||
email: string,
|
||||
): Promise<void> {
|
||||
await user.click(screen.getAllByTestId(/^invite-email-.*-field$/)[rowIndex]);
|
||||
await user.paste(email);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ interface Props {
|
||||
placeholder?: string;
|
||||
// Rendered at the end of the search row (e.g. the New Dashboard action).
|
||||
rightSlot?: ReactNode;
|
||||
// Rendered in the filters row after the chips. A function receives the draft.
|
||||
// Rendered in the filters row before the chips. A function receives the draft.
|
||||
extraFilters?: ReactNode | ((api: ExtraFiltersApi) => ReactNode);
|
||||
// Shows Clear even when the query is empty.
|
||||
hasExtraFilters?: boolean;
|
||||
@@ -142,6 +142,9 @@ function FilterZone({
|
||||
className={styles.filterControls}
|
||||
data-testid={`${testIdPrefix}-filter-zone`}
|
||||
>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
<FilterChips
|
||||
{...createdByProps}
|
||||
updated={reflected.updated}
|
||||
@@ -150,9 +153,6 @@ function FilterZone({
|
||||
onApply={run}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{typeof extraFilters === 'function'
|
||||
? extraFilters({ draft, applyDraft, setDraft })
|
||||
: extraFilters}
|
||||
{(!isEmpty || hasExtraFilters) && (
|
||||
<Button
|
||||
disabledTooltip={undefined}
|
||||
|
||||
@@ -43,6 +43,7 @@ function MultiSelectFilter({
|
||||
allowClear
|
||||
className={cx(styles.select, styles.selectWide)}
|
||||
placeholder={placeholder}
|
||||
aria-label={placeholder}
|
||||
value={value}
|
||||
options={options}
|
||||
optionFilterProp="label"
|
||||
@@ -52,7 +53,10 @@ function MultiSelectFilter({
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div className={styles.checkOption}>
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
data-testid={`${testId}-option-${String(option.value)}`}
|
||||
>
|
||||
<div className={styles.checkOptionBox}>
|
||||
<Checkbox
|
||||
color="primary"
|
||||
|
||||
@@ -34,7 +34,7 @@ describe('InvalidQueryState', () => {
|
||||
});
|
||||
|
||||
it('runs the callback, then opens support', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onContactSupport = jest.fn();
|
||||
render(
|
||||
<InvalidQueryState
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { type MouseEvent, useCallback, useMemo, useRef } from 'react';
|
||||
import {
|
||||
type FocusEvent,
|
||||
type MouseEvent,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -27,7 +33,7 @@ import styles from './SearchBar.module.scss';
|
||||
interface Props {
|
||||
value: string;
|
||||
grammar: DslGrammar;
|
||||
// Ids: `${testIdPrefix}`, `-submit`, `-dirty`.
|
||||
// Ids: `${testIdPrefix}`, `-field` (the editable area), `-submit`, `-dirty`.
|
||||
testIdPrefix: string;
|
||||
onChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
@@ -67,10 +73,25 @@ function SearchBar({
|
||||
const onSubmitRef = useRef(handleSubmit);
|
||||
onSubmitRef.current = handleSubmit;
|
||||
|
||||
// Leaving the box runs an unrun draft, e.g. terms picked from the suggestions.
|
||||
// A blur from switching windows or tabs does not.
|
||||
const handleBlur = useCallback(
|
||||
(event: FocusEvent<HTMLDivElement>): void => {
|
||||
const stillInside = event.currentTarget.contains(
|
||||
event.relatedTarget as Node | null,
|
||||
);
|
||||
if (!stillInside && dirty && !disabled && document.hasFocus()) {
|
||||
handleSubmit();
|
||||
}
|
||||
},
|
||||
[dirty, disabled, handleSubmit],
|
||||
);
|
||||
|
||||
const extensions = useMemo(
|
||||
() => [
|
||||
dslHighlight,
|
||||
editorTheme,
|
||||
EditorView.contentAttributes.of({ 'data-testid': `${testIdPrefix}-field` }),
|
||||
// Wrap a long query onto the next line instead of scrolling horizontally.
|
||||
EditorView.lineWrapping,
|
||||
// Read-only is not enough: these open the list on click and accepting an
|
||||
@@ -122,12 +143,15 @@ function SearchBar({
|
||||
]),
|
||||
),
|
||||
],
|
||||
[disabled],
|
||||
[disabled, testIdPrefix],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
<div className={cx(styles.field, { [styles.disabled]: disabled })}>
|
||||
<div
|
||||
className={cx(styles.field, { [styles.disabled]: disabled })}
|
||||
onBlur={handleBlur}
|
||||
>
|
||||
<Search
|
||||
size={12}
|
||||
color={Color.BG_VANILLA_400}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import SearchBar from '../SearchBar';
|
||||
|
||||
type SearchBarProps = ComponentProps<typeof SearchBar>;
|
||||
|
||||
const GRAMMAR: DslGrammar = {
|
||||
fields: [{ key: 'name', type: 'string' }],
|
||||
dynamicKey: { detail: 'tag', prefix: '' },
|
||||
};
|
||||
|
||||
function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
|
||||
onSubmit: jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
onSubmitted: jest.MockedFunction<NonNullable<SearchBarProps['onSubmitted']>>;
|
||||
} {
|
||||
const onSubmit = jest.fn() as jest.MockedFunction<SearchBarProps['onSubmit']>;
|
||||
const onSubmitted = jest.fn() as jest.MockedFunction<
|
||||
NonNullable<SearchBarProps['onSubmitted']>
|
||||
>;
|
||||
render(
|
||||
<>
|
||||
<SearchBar
|
||||
value="name = 'x'"
|
||||
grammar={GRAMMAR}
|
||||
testIdPrefix="list-search"
|
||||
onChange={jest.fn()}
|
||||
onSubmit={onSubmit}
|
||||
onSubmitted={onSubmitted}
|
||||
dirty={props.dirty}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
</>,
|
||||
);
|
||||
return { onSubmit, onSubmitted };
|
||||
}
|
||||
|
||||
function searchContent(): HTMLElement {
|
||||
return within(screen.getByTestId('list-search')).getByRole('textbox');
|
||||
}
|
||||
|
||||
describe('SearchBar — run on blur', () => {
|
||||
let hasFocus: jest.SpyInstance<boolean, []>;
|
||||
|
||||
beforeEach(() => {
|
||||
// jsdom reports no focus once it leaves the editor; a focused browser window does.
|
||||
hasFocus = jest.spyOn(document, 'hasFocus').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('runs an unrun draft when focus leaves the box', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit, onSubmitted } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(onSubmitted).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('does nothing when the draft was already run', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: false });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing when focus leaves the window', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
hasFocus.mockReturnValue(false);
|
||||
await user.click(screen.getByTestId('outside'));
|
||||
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('runs once when Run query is clicked with an unrun draft', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { onSubmit } = renderSearchBar({ dirty: true });
|
||||
|
||||
await user.click(searchContent());
|
||||
await user.click(screen.getByTestId('list-search-submit'));
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
.headerZone {
|
||||
// Sticks to the top of a scrolling list so the heading and filters stay put
|
||||
// while results scroll beneath. The DSL suggestion popup (z-index 1000) still
|
||||
// layers above it.
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
gap: 14px;
|
||||
padding: 20px 24px;
|
||||
background: var(--l2-background);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import styles from './ListHeaderZone.module.scss';
|
||||
|
||||
interface Props {
|
||||
/** Rendered regardless of whether the list has anything in it. */
|
||||
children: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ListHeaderZone({ children, testId }: Props): JSX.Element {
|
||||
return (
|
||||
<div className={styles.headerZone} data-testid={testId}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ListHeaderZone;
|
||||
@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('selects a view by id', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-view-2`));
|
||||
@@ -61,7 +61,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('filters views by name and says when none match', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderRail();
|
||||
const search = screen.getByTestId(`${PREFIX}-view-search-field`);
|
||||
|
||||
@@ -109,7 +109,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('offers save, save as and reset for a modified custom view', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({
|
||||
activeViewId: 'view-1',
|
||||
@@ -138,7 +138,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('saves the current filters as a named view from the dialog', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({ onViewSaved });
|
||||
|
||||
@@ -164,7 +164,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('opens the save dialog empty again after a cancel', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail({ isModified: true });
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-save-as-new`));
|
||||
@@ -183,7 +183,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('renames a custom view from a dialog filled with its name', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewRenamed = jest.fn();
|
||||
const props = renderRail({ onViewRenamed });
|
||||
|
||||
@@ -206,7 +206,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('refills the rename dialog with the name of the view it opens for', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
|
||||
|
||||
@@ -1,40 +1,32 @@
|
||||
import React, { ComponentType, Suspense } from 'react';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitForElementToBeRemoved,
|
||||
} from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import Loadable from './index';
|
||||
|
||||
// Sample component to be loaded lazily
|
||||
function SampleComponent(): JSX.Element {
|
||||
return <div>Sample Component</div>;
|
||||
return <div data-testid="sample-component">Sample Component</div>;
|
||||
}
|
||||
|
||||
const loadSampleComponent = (): Promise<{
|
||||
default: ComponentType;
|
||||
}> =>
|
||||
new Promise<{ default: ComponentType }>((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({ default: SampleComponent });
|
||||
}, 500);
|
||||
});
|
||||
}> => Promise.resolve({ default: SampleComponent });
|
||||
|
||||
describe('Loadable', () => {
|
||||
it('should render the lazily loaded component', async () => {
|
||||
const LoadableSampleComponent = Loadable(loadSampleComponent);
|
||||
|
||||
const { container } = render(
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
render(
|
||||
<Suspense fallback={<div data-testid="loading">Loading...</div>}>
|
||||
<LoadableSampleComponent />
|
||||
</Suspense>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
|
||||
|
||||
expect(container.querySelector('div')).toHaveTextContent('Sample Component');
|
||||
expect(screen.getByTestId('loading')).toBeInTheDocument();
|
||||
await expect(
|
||||
screen.findByTestId('sample-component'),
|
||||
).resolves.toHaveTextContent('Sample Component');
|
||||
expect(screen.queryByTestId('loading')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call lazy with the provided import path', () => {
|
||||
|
||||
@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log link from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -128,7 +128,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open when a ⋯ menu item is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -152,7 +152,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('calls handleOpenInExplorer when "Open in Explorer" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const handleOpenInExplorer = jest.fn();
|
||||
|
||||
renderDrawer({ handleOpenInExplorer });
|
||||
@@ -163,7 +163,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes from the close button and from Escape', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -176,7 +176,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes on a mousedown outside the drawer and not on one inside it', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -196,7 +196,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open on a mousedown in a data-log-detail-ignore region', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -258,7 +258,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates to the next / previous log with the Down / Up arrow keys', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1'), makeLog('log-2')];
|
||||
const onNavigateLog = jest.fn();
|
||||
const onScrollToLog = jest.fn();
|
||||
@@ -276,7 +276,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('does not navigate past the first log on ArrowUp', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
@@ -287,7 +287,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates via the header up / down buttons and disables them at boundaries', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
|
||||
@@ -1,46 +1,39 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import LogStateIndicator from './LogStateIndicator';
|
||||
|
||||
describe('LogStateIndicator', () => {
|
||||
it('renders correctly with default props', () => {
|
||||
const { container } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
render(<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />);
|
||||
const indicator = screen.getByTestId('log-state-indicator');
|
||||
expect(indicator).toHaveClass('log-state-indicator');
|
||||
expect(indicator).not.toHaveClass('isActive');
|
||||
expect(within(indicator).getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator.classList.contains('log-state-indicator')).toBe(true);
|
||||
expect(indicator.classList.contains('isActive')).toBe(false);
|
||||
expect(container.querySelector('.line')).toBeTruthy();
|
||||
expect(
|
||||
container.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('renders correctly with different types', () => {
|
||||
const { container: containerInfo } = render(
|
||||
const { rerender } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerInfo.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
|
||||
const { container: containerWarning } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="WARNING" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerWarning
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-warn-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-warn-0',
|
||||
);
|
||||
|
||||
const { container: containerError } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="ERROR" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerError
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-error-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-error-0',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,8 +138,11 @@ function LogStateIndicator({
|
||||
const severityClass = getSeverityClass(severityText, severityNumber);
|
||||
|
||||
return (
|
||||
<div className="log-state-indicator">
|
||||
<div className={cx('line', fontSize, severityClass)} />
|
||||
<div className="log-state-indicator" data-testid="log-state-indicator">
|
||||
<div
|
||||
className={cx('line', fontSize, severityClass)}
|
||||
data-testid="log-state-indicator-line"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,7 +128,9 @@ function OptionsMenu({
|
||||
>
|
||||
<span className="menu-row">
|
||||
{size}
|
||||
{fontSizeValue === size && <Check size={14} />}
|
||||
{fontSizeValue === size && (
|
||||
<Check size={14} data-testid="font-size-option-check" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
@@ -156,7 +158,7 @@ function OptionsMenu({
|
||||
</Button>
|
||||
</div>
|
||||
<div className="horizontal-line" />
|
||||
<div className="menu-container">
|
||||
<div className="menu-container" data-testid="format-options-menu">
|
||||
<div className="title">FORMAT</div>
|
||||
|
||||
<div className="menu-items">
|
||||
@@ -170,7 +172,9 @@ function OptionsMenu({
|
||||
<div className={cx('item-label')}>
|
||||
{item.label}
|
||||
|
||||
{selectedItem === item.key && <Check size={12} />}
|
||||
{selectedItem === item.key && (
|
||||
<Check size={12} data-testid="format-check-icon" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
|
||||
@@ -34,13 +35,14 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
mockUpdateFormatting.mockClear();
|
||||
});
|
||||
|
||||
function setup(): {
|
||||
async function setup(): Promise<{
|
||||
user: ReturnType<typeof userEvent.setup>;
|
||||
getByTestId: ReturnType<typeof render>['getByTestId'];
|
||||
findItemByLabel: (label: string) => Element | undefined;
|
||||
formatOnChange: jest.Mock<any, any>;
|
||||
maxLinesOnChange: jest.Mock<any, any>;
|
||||
fontSizeOnChange: jest.Mock<any, any>;
|
||||
} {
|
||||
}> {
|
||||
const user = userEvent.setup();
|
||||
const items = [
|
||||
{ key: 'raw', label: 'Raw', data: { title: 'max lines per row' } },
|
||||
{ key: 'list', label: 'Default' },
|
||||
@@ -76,16 +78,11 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Open the popover menu by default for each test
|
||||
const formatButton = getByTestId('periscope-btn-format-options');
|
||||
fireEvent.click(formatButton);
|
||||
|
||||
const getMenuItems = (): Element[] =>
|
||||
Array.from(document.querySelectorAll('.menu-items .item'));
|
||||
const findItemByLabel = (label: string): Element | undefined =>
|
||||
getMenuItems().find((el) => (el.textContent || '').includes(label));
|
||||
await user.click(formatButton);
|
||||
|
||||
return {
|
||||
user,
|
||||
getByTestId,
|
||||
findItemByLabel,
|
||||
formatOnChange,
|
||||
maxLinesOnChange,
|
||||
fontSizeOnChange,
|
||||
@@ -94,31 +91,36 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Covers: opens menu, changes format selection, updates max-lines, changes font size
|
||||
it('opens and toggles format selection', async () => {
|
||||
const { findItemByLabel, formatOnChange } = setup();
|
||||
const { user, formatOnChange } = await setup();
|
||||
|
||||
// Assert initial selection
|
||||
const columnItem = findItemByLabel('Column') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(columnItem.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-table')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Change selection to 'Raw'
|
||||
const rawItem = findItemByLabel('Raw') as Element;
|
||||
fireEvent.click(rawItem as HTMLElement);
|
||||
await user.click(screen.getByTestId('format-option-raw'));
|
||||
await waitFor(() => {
|
||||
const rawEl = findItemByLabel('Raw') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(rawEl.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-raw')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(formatOnChange).toHaveBeenCalledWith('raw');
|
||||
});
|
||||
|
||||
it('increments max-lines and calls onChange', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
|
||||
// Increment max lines
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const initial = Number(input.value);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
await user.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Number(input.value)).toBe(initial + 1);
|
||||
@@ -129,9 +131,8 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('clamps a typed max-lines value to 10', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '15');
|
||||
@@ -142,10 +143,9 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('stops max-lines at 10', async () => {
|
||||
const { getByTestId } = setup();
|
||||
const { user, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const increment = screen.getByRole('button', { name: 'More lines per row' });
|
||||
const user = userEvent.setup();
|
||||
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await user.click(increment);
|
||||
@@ -155,19 +155,23 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('changes font size to MEDIUM and calls onChange', async () => {
|
||||
const { fontSizeOnChange, getByTestId } = setup();
|
||||
const { user, fontSizeOnChange, getByTestId } = await setup();
|
||||
// Open font dropdown
|
||||
fireEvent.click(getByTestId('font-size-select'));
|
||||
await user.click(getByTestId('font-size-select'));
|
||||
|
||||
// Choose MEDIUM
|
||||
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
await user.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.MEDIUM}`)).getByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.SMALL}`)).queryByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() => {
|
||||
@@ -212,16 +216,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
renderWithOnOpen(undefined, 'table');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render "Edit columns" row when format is not table', () => {
|
||||
renderWithOnOpen(jest.fn(), 'raw');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
|
||||
@@ -233,7 +237,7 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
expect(onOpenColumns).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => {
|
||||
// Popover content unmounts on close.
|
||||
expect(document.querySelector('.menu-container')).toBeNull();
|
||||
expect(screen.queryByTestId('format-option-table')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,8 +74,7 @@ function Harness({
|
||||
}
|
||||
|
||||
const getView = (): EditorView => {
|
||||
const dom = document.querySelector('.cm-editor');
|
||||
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
|
||||
const view = EditorView.findFromDOM(screen.getByTestId('markdown-editor'));
|
||||
if (!view) {
|
||||
throw new Error('editor view not mounted');
|
||||
}
|
||||
@@ -151,11 +150,9 @@ describe('MarkdownEditor', () => {
|
||||
render(<Harness initialValue={'## Runbook\nowner {{team}}'} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.cm-md-heading')).toBeInTheDocument();
|
||||
expect(screen.getByText('## Runbook')).toHaveClass('cm-md-heading');
|
||||
});
|
||||
expect(document.querySelector('.cm-md-variable')).toHaveTextContent(
|
||||
'{{team}}',
|
||||
);
|
||||
expect(screen.getByText('{{team}}')).toHaveClass('cm-md-variable');
|
||||
});
|
||||
|
||||
describe('uncontrolled document', () => {
|
||||
|
||||
@@ -189,7 +189,13 @@ function MembersTable({
|
||||
<span className="members-pagination-range">
|
||||
{range[0]} — {range[1]}
|
||||
</span>
|
||||
<span className="members-pagination-total"> of {_total}</span>
|
||||
<span
|
||||
className="members-pagination-total"
|
||||
data-testid="members-pagination-total"
|
||||
>
|
||||
{' '}
|
||||
of {_total}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('MembersTable', () => {
|
||||
const onRowClick = jest.fn() as jest.MockedFunction<
|
||||
(member: MemberRow) => void
|
||||
>;
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<MembersTable
|
||||
@@ -88,7 +88,7 @@ describe('MembersTable', () => {
|
||||
|
||||
it('renders DELETED badge and calls onRowClick when a deleted member row is clicked', async () => {
|
||||
const onRowClick = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const deletedMember: MemberRow = {
|
||||
id: 'user-del',
|
||||
name: 'Dave Deleted',
|
||||
@@ -129,7 +129,7 @@ describe('MembersTable', () => {
|
||||
});
|
||||
|
||||
it('hides pagination when total does not exceed pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -139,12 +139,12 @@ describe('MembersTable', () => {
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
screen.queryByTestId('members-pagination-total'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows pagination when total exceeds pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -153,11 +153,8 @@ describe('MembersTable', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.members-pagination-total'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('members-pagination-total')).toHaveTextContent(
|
||||
'of 25',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import MessageTip from './index';
|
||||
|
||||
@@ -35,13 +35,13 @@ describe('MessageTip', () => {
|
||||
// taken from antd docs
|
||||
// https://github.com/ant-design/ant-design/blob/master/components/alert/__tests__/index.test.tsx
|
||||
it('custom action', () => {
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<MessageTip
|
||||
show
|
||||
message="Success Tips"
|
||||
action={<button type="button">Close</button>}
|
||||
/>,
|
||||
);
|
||||
expect(container.firstChild).toMatchSnapshot();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
|
||||
|
||||
exports[`MessageTip custom action 1`] = `
|
||||
.c0 {
|
||||
<DocumentFragment>
|
||||
.c0 {
|
||||
-webkit-align-items: center;
|
||||
-webkit-box-align: center;
|
||||
-ms-flex-align: center;
|
||||
@@ -9,46 +10,47 @@ exports[`MessageTip custom action 1`] = `
|
||||
}
|
||||
|
||||
<div
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-content"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
class="ant-alert-content"
|
||||
>
|
||||
Success Tips
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
>
|
||||
Success Tips
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
@@ -632,7 +632,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -746,6 +750,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onKeyDown={(e): void => {
|
||||
if ((e.key === 'Enter' || e.key === SPACEKEY) && isActive) {
|
||||
e.stopPropagation();
|
||||
@@ -777,7 +782,9 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{(option.type === 'custom' || option.type === 'regex') && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
{option.value && ensureValidOption(option.value) && (
|
||||
<Button
|
||||
@@ -1562,6 +1569,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-multiselect-dropdown"
|
||||
data-testid="custom-multiselect-dropdown"
|
||||
onMouseDown={handleDropdownMouseDown}
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
@@ -1583,6 +1591,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
active: activeIndex === 0,
|
||||
})}
|
||||
key={`all-option-${allOptionsSelected}`}
|
||||
data-testid="all-option"
|
||||
id="option-0"
|
||||
onMouseEnter={(): void => {
|
||||
setActiveIndex(0);
|
||||
@@ -1641,7 +1650,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divider" />
|
||||
<div className="divider" data-testid="all-option-divider" />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1711,7 +1720,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
)}
|
||||
|
||||
{/* Navigation help footer */}
|
||||
<div className="navigation-footer" role="note">
|
||||
<div
|
||||
className="navigation-footer"
|
||||
role="note"
|
||||
data-testid="navigation-footer"
|
||||
>
|
||||
{!loading &&
|
||||
!errorMessage &&
|
||||
!noDataMessage &&
|
||||
@@ -1726,7 +1739,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1734,7 +1747,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1744,7 +1757,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && !waitingMessage && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
@@ -1959,6 +1972,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
'ant-select-selection-item-active': isActive,
|
||||
'ant-select-selection-item-selected': isSelected,
|
||||
})}
|
||||
data-testid={`selected-tag-${value}`}
|
||||
style={
|
||||
isActive || isSelected
|
||||
? {
|
||||
|
||||
@@ -170,7 +170,11 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -220,6 +224,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
handleSelection();
|
||||
@@ -241,7 +246,9 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{option.type === 'custom' && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -268,6 +275,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
() => (
|
||||
<X
|
||||
size="md"
|
||||
data-testid="custom-select-clear"
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
if (onChange) {
|
||||
@@ -528,6 +536,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-select-dropdown"
|
||||
data-testid="custom-select-dropdown"
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
onScroll={handleDropdownScroll}
|
||||
@@ -587,7 +596,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -595,7 +604,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -605,7 +614,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
import type { CustomMultiSelectProps } from '../types';
|
||||
|
||||
// Mock scrollIntoView which isn't available in JSDOM
|
||||
window.HTMLElement.prototype.scrollIntoView = jest.fn();
|
||||
@@ -49,6 +50,26 @@ const mockGroupedOptions = [
|
||||
},
|
||||
];
|
||||
|
||||
function StatefulMultiSelect({
|
||||
initialValue,
|
||||
onChange,
|
||||
}: {
|
||||
initialValue: string[];
|
||||
onChange: CustomMultiSelectProps['onChange'];
|
||||
}): JSX.Element {
|
||||
const [value, setValue] = useState<string[] | string>(initialValue);
|
||||
return (
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
value={value}
|
||||
onChange={(next, option): void => {
|
||||
onChange?.(next, option);
|
||||
setValue(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
let user: ReturnType<typeof userEvent.setup>;
|
||||
let mockOnChange: jest.Mock;
|
||||
@@ -114,16 +135,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Verify the component renders without crashing
|
||||
expect(combobox).toBeInTheDocument();
|
||||
@@ -141,30 +154,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -188,49 +191,31 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should filter to show only Frontend and Backend with highlighted "end"
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "end" text in the options
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
|
||||
// Check that Frontend and Backend options are present with highlighted text
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Front') &&
|
||||
label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
const hasBackendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Back') && label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveTextContent(
|
||||
'Backend',
|
||||
);
|
||||
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
expect(hasBackendOption).toBe(true);
|
||||
|
||||
// Other options should be filtered out
|
||||
const hasDatabaseOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Database'),
|
||||
);
|
||||
const hasApiGatewayOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('API Gateway'),
|
||||
);
|
||||
|
||||
expect(hasDatabaseOption).toBe(false);
|
||||
expect(hasApiGatewayOption).toBe(false);
|
||||
expect(
|
||||
screen.queryByTestId('option-item-database'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('option-item-api-gateway'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,15 +231,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Type comma-separated values
|
||||
await user.type(searchInput, 'test1, test2, test3');
|
||||
}
|
||||
// Type comma-separated values
|
||||
await user.type(combobox, 'test1, test2, test3');
|
||||
|
||||
// Press Enter to create the comma-separated chips
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -294,14 +272,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-multiselect-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-label-text') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top (after ALL option if present)
|
||||
expect(optionTexts[0]).toBe('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toBe(screen.getByTestId('option-item-database'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -319,30 +296,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front' and highlight search term
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -362,21 +329,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -393,14 +352,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -411,13 +363,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -445,23 +395,19 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('option-item-frontend');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
// The active option should be an option in the dropdown
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option (goes back to ALL)
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('all-option');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
expect(activeOption?.textContent).toContain('ALL');
|
||||
expect(activeOption).toHaveTextContent('ALL');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -499,19 +445,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Tab again to move to next option
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -558,10 +499,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Delete the active chip
|
||||
@@ -575,11 +515,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify that the active chip (backend) is highlighted for deletion
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
expect(activeChip).toHaveTextContent('backend');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -688,9 +626,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByRole('checkbox'));
|
||||
|
||||
@@ -726,9 +662,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByText('Toggle'));
|
||||
|
||||
@@ -751,8 +685,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Database')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Gateway')).toBeInTheDocument();
|
||||
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
expect(screen.getByText('Refreshing values...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -770,8 +703,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -813,21 +745,17 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// All chips should be selected (have selected class)
|
||||
const selectedChips = document.querySelectorAll(
|
||||
'.ant-select-selection-item-selected',
|
||||
);
|
||||
const selectedChips = screen
|
||||
.getAllByTestId(/^selected-tag-/)
|
||||
.filter((chip) =>
|
||||
chip.classList.contains('ant-select-selection-item-selected'),
|
||||
);
|
||||
expect(selectedChips.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify that all expected chips are present AND selected
|
||||
const frontendChip = screen
|
||||
.getByText('frontend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const backendChip = screen
|
||||
.getByText('backend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const databaseChip = screen
|
||||
.getByText('database')
|
||||
.closest('.ant-select-selection-item');
|
||||
const frontendChip = screen.getByTestId('selected-tag-frontend');
|
||||
const backendChip = screen.getByTestId('selected-tag-backend');
|
||||
const databaseChip = screen.getByTestId('selected-tag-database');
|
||||
|
||||
expect(frontendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
expect(backendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
@@ -850,11 +778,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
if (clearButton) {
|
||||
await user.click(clearButton as Element);
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
}
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
});
|
||||
|
||||
it('CA-03: Individual chip removal', async () => {
|
||||
@@ -867,12 +792,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
// Find and click the close button on a chip
|
||||
const removeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
const removeButtons = screen.getAllByLabelText(/^Remove tag /);
|
||||
expect(removeButtons).toHaveLength(2);
|
||||
|
||||
await user.click(removeButtons[1] as Element);
|
||||
await user.click(removeButtons[1]);
|
||||
|
||||
// Should call onChange with one item removed
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -911,9 +834,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Dropdown should be hidden (not completely removed from DOM)
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(dropdown).toHaveStyle('pointer-events: none');
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -951,14 +875,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-input');
|
||||
}
|
||||
await user.type(combobox, 'custom-input');
|
||||
|
||||
// Press Enter in input field
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -984,18 +901,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'search-text');
|
||||
}
|
||||
await user.type(combobox, 'search-text');
|
||||
|
||||
// Verify search text is in input
|
||||
await waitFor(() => {
|
||||
expect(searchInput).toHaveValue('search-text');
|
||||
expect(combobox).toHaveValue('search-text');
|
||||
});
|
||||
|
||||
// Press Escape to close dropdown
|
||||
@@ -1003,9 +913,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close and search text should be cleared
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(searchInput).toHaveValue('');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(combobox).toHaveValue('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1029,8 +938,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(allOption).toBeInTheDocument();
|
||||
|
||||
// Check for divider after ALL option
|
||||
const divider = document.querySelector('.divider');
|
||||
expect(divider).toBeInTheDocument();
|
||||
expect(screen.getByTestId('all-option-divider')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1086,8 +994,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show navigation footer
|
||||
const footer = document.querySelector('.navigation-footer');
|
||||
expect(footer).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-footer')).toBeInTheDocument();
|
||||
|
||||
// Should show navigation hint
|
||||
expect(screen.getByText('to navigate')).toBeInTheDocument();
|
||||
@@ -1161,10 +1068,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
describe('Advanced Keyboard Navigation (AKN)', () => {
|
||||
it('AKN-01: Shift + Arrow + Del chip deletion', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
<StatefulMultiSelect
|
||||
initialValue={['frontend', 'backend', 'database']}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend', 'backend', 'database']}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -1176,12 +1082,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip - verify initial chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we're on the last chip (database)
|
||||
expect(activeChip?.textContent).toContain('database');
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Shift + Arrow to navigate to previous chip
|
||||
@@ -1189,12 +1093,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify we're on a different chip (backend)
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we moved to the previous chip (backend)
|
||||
expect(activeChip?.textContent).toContain('backend');
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Del to delete the active chip
|
||||
@@ -1203,8 +1105,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
// Verify the chip was deleted
|
||||
await waitFor(() => {
|
||||
// Check that the backend chip is no longer present
|
||||
const backendChip = document.querySelector('.ant-select-selection-item');
|
||||
expect(backendChip?.textContent).not.toContain('backend');
|
||||
expect(
|
||||
screen.queryByTestId('selected-tag-backend'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Verify onChange was called with the updated value (without backend)
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -1235,9 +1138,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close - check for hidden state
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
// The dropdown should be hidden with the hidden class
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1256,32 +1158,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const labelElement = item.querySelector('.option-label-text');
|
||||
return labelElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text should contain "front"
|
||||
@@ -1325,12 +1215,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should create custom value)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -1364,11 +1249,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith([], []);
|
||||
@@ -1426,19 +1308,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -1469,25 +1345,16 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1570,8 +1437,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Escape}');
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,9 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -29,9 +30,6 @@ const mockOptions = [
|
||||
{ label: 'Option 3', value: 'option3' },
|
||||
];
|
||||
|
||||
// CSS selector for retry button
|
||||
const RETRY_BUTTON_SELECTOR = '[data-testid="retry-button"]';
|
||||
|
||||
describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -61,8 +59,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Check that retry button (ReloadOutlined icon) is present
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
|
||||
@@ -88,11 +85,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
expect(screen.getByText(errorMessage)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call onRetry function when retry button is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const mockOnRetry = jest.fn();
|
||||
const errorMessage = 'Internal Server Error (500)';
|
||||
|
||||
@@ -108,7 +105,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Wait for dropdown to appear
|
||||
await waitFor(() => {
|
||||
@@ -116,10 +113,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Find and click the retry button
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryButton as Element);
|
||||
await user.click(screen.getByTestId('retry-button'));
|
||||
|
||||
// Verify onRetry was called
|
||||
expect(mockOnRetry).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -4,9 +4,10 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -156,6 +157,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('removes a tag when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleChange = jest.fn();
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
@@ -166,10 +168,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
);
|
||||
|
||||
// Find close button on Option 1 tag and click it
|
||||
const closeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
fireEvent.click(closeButtons[0]);
|
||||
await user.click(screen.getByLabelText('Remove tag option1'));
|
||||
|
||||
// Verify onChange was called with remaining option
|
||||
expect(handleChange).toHaveBeenCalledWith(
|
||||
@@ -179,39 +178,24 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('filters options when searching', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Type into search box - get input directly
|
||||
const inputElement = selectElement.querySelector('input');
|
||||
if (inputElement) {
|
||||
fireEvent.change(inputElement, { target: { value: '2' } });
|
||||
}
|
||||
// Type into search box - the combobox is the search input
|
||||
await user.type(selectElement, '2');
|
||||
|
||||
// Wait for the dropdown filtering to happen
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector(
|
||||
'.custom-multiselect-dropdown',
|
||||
);
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Verify Option 2 is visible in the dropdown
|
||||
const options = document.querySelectorAll('.option-label-text');
|
||||
let foundOption2 = false;
|
||||
|
||||
options.forEach((option) => {
|
||||
const text = option.textContent || '';
|
||||
if (text.includes('Option 2')) {
|
||||
foundOption2 = true;
|
||||
}
|
||||
});
|
||||
|
||||
expect(foundOption2).toBe(true);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('option-item-option1')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(
|
||||
within(screen.getByTestId('custom-multiselect-dropdown'))
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((option) => option.dataset.testid),
|
||||
).toStrictEqual(['option-item-2', 'option-item-option2']);
|
||||
});
|
||||
|
||||
it('renders grouped options correctly', async () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -67,34 +66,19 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Check that custom value appears in dropdown with custom tag
|
||||
await waitFor(() => {
|
||||
// Find the custom option with "fro" text and "Custom" badge
|
||||
const customOptions = screen.getAllByText('fro');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-fro');
|
||||
expect(customOption).toHaveTextContent('fro');
|
||||
|
||||
// Verify it has the custom badge
|
||||
const optionItem = customOption?.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
expect(badge).toBeInTheDocument();
|
||||
expect(badge?.textContent).toBe('Custom');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the custom value
|
||||
@@ -120,30 +104,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -174,14 +148,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-content') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top
|
||||
expect(optionTexts[0]).toContain('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toHaveTextContent('Database');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -197,30 +168,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front'
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -238,21 +199,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -267,14 +220,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -285,13 +231,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -313,19 +257,15 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
// Verify it's the first option (Frontend)
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Frontend');
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,8 +350,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Tab}');
|
||||
|
||||
// Should still be within dropdown context
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -453,8 +392,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -471,8 +409,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -605,8 +542,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Focus should remain manageable
|
||||
@@ -679,8 +615,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -714,8 +649,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -732,32 +666,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const contentElement = item.querySelector('.option-content');
|
||||
return contentElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text includes "Custom" badge, so check for "front" in the text
|
||||
@@ -807,12 +729,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should close dropdown)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -847,11 +764,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -870,11 +784,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should clear the single selection
|
||||
expect(mockOnChange).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -927,19 +838,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -962,12 +867,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
// Should be able to type even with loading state
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'test');
|
||||
}
|
||||
await user.type(combobox, 'test');
|
||||
|
||||
// Should not be blocked by loading spinner
|
||||
expect(combobox).not.toBeDisabled();
|
||||
@@ -986,25 +886,16 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1076,8 +967,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close after selection in single select
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -93,11 +99,12 @@ describe('CustomSelect Component', () => {
|
||||
// Dropdown should only show Option 2
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector('.custom-select-dropdown');
|
||||
const dropdownElement = screen.getByTestId('custom-select-dropdown');
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Use a simple approach to verify filtering
|
||||
const allOptionsInDropdown = document.querySelectorAll('.option-item');
|
||||
const allOptionsInDropdown =
|
||||
within(dropdownElement).queryAllByTestId(/^option-item-/);
|
||||
let foundOption2 = false;
|
||||
|
||||
allOptionsInDropdown.forEach((option) => {
|
||||
|
||||
@@ -40,7 +40,7 @@ function ListViewOrderBy({
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [selectOptions, setSelectOptions] = useState<
|
||||
{ label: string; value: string }[]
|
||||
{ label: string; value: string; 'data-testid': string }[]
|
||||
>([]);
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
@@ -75,8 +75,16 @@ function ListViewOrderBy({
|
||||
|
||||
setSelectOptions(
|
||||
uniqueKeys.flatMap((key) => [
|
||||
{ label: `${key} (desc)`, value: `${key}:desc` },
|
||||
{ label: `${key} (asc)`, value: `${key}:asc` },
|
||||
{
|
||||
label: `${key} (desc)`,
|
||||
value: `${key}:desc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
{
|
||||
label: `${key} (asc)`,
|
||||
value: `${key}:asc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
]),
|
||||
);
|
||||
}, [data, searchInput, extraKeysSignature]);
|
||||
|
||||
@@ -59,9 +59,9 @@ const openDropdown = (): void => {
|
||||
};
|
||||
|
||||
const getOptionLabels = (): string[] =>
|
||||
Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(
|
||||
(node) => node.textContent ?? '',
|
||||
);
|
||||
screen
|
||||
.queryAllByTestId('list-view-order-by-option')
|
||||
.map((node) => node.textContent ?? '');
|
||||
|
||||
describe('ListViewOrderBy', () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import OverflowInputToolTip from './OverflowInputToolTip';
|
||||
|
||||
const TOOLTIP_INNER_SELECTOR = '.ant-tooltip-inner';
|
||||
// Utility to mock overflow behaviour on inputs / elements.
|
||||
// Stubs HTMLElement.prototype.clientWidth, scrollWidth and offsetWidth used by component.
|
||||
function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
@@ -22,21 +21,17 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
function queryTooltipInner(): HTMLElement | null {
|
||||
// find element that has role="tooltip" (could be the inner itself)
|
||||
const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');
|
||||
if (!tooltip) {
|
||||
return document.querySelector(TOOLTIP_INNER_SELECTOR);
|
||||
}
|
||||
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
|
||||
|
||||
// if the role element is already the inner, return it; otherwise return its descendant
|
||||
if (tooltip.classList.contains('ant-tooltip-inner')) {
|
||||
return tooltip;
|
||||
}
|
||||
return (
|
||||
(tooltip.querySelector(TOOLTIP_INNER_SELECTOR) as HTMLElement) ??
|
||||
document.querySelector(TOOLTIP_INNER_SELECTOR)
|
||||
);
|
||||
async function hoverPastOpenDelay(element: HTMLElement): Promise<void> {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
await user.hover(element);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(ANTD_TOOLTIP_OPEN_DELAY_MS * 2);
|
||||
});
|
||||
}
|
||||
|
||||
describe('OverflowInputToolTip', () => {
|
||||
@@ -44,6 +39,10 @@ describe('OverflowInputToolTip', () => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('shows tooltip when content overflows and input is clamped at maxAutoWidth', async () => {
|
||||
mockOverflow(150, 250); // clientWidth >= maxAutoWidth (150), scrollWidth > clientWidth
|
||||
|
||||
@@ -51,16 +50,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).not.toBeNull();
|
||||
});
|
||||
|
||||
const tooltipInner = queryTooltipInner();
|
||||
if (!tooltipInner) {
|
||||
throw new Error('Tooltip inner not found');
|
||||
}
|
||||
const tooltip = await screen.findByRole('tooltip');
|
||||
expect(
|
||||
within(tooltipInner).getByText('Very long overflowing text'),
|
||||
within(tooltip).getByText('Very long overflowing text'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -69,11 +61,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Short text" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
|
||||
@@ -81,11 +71,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Long but input not clamped" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uncontrolled input allows typing', async () => {
|
||||
@@ -102,24 +90,20 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Overflowing!" disabled />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
|
||||
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = container.querySelector('.overflow-input-mirror');
|
||||
const input = container.querySelector('input') as HTMLInputElement | null;
|
||||
render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = screen.getByTestId('overflow-input-mirror');
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
expect(mirror).toBeTruthy();
|
||||
expect(mirror?.textContent).toBe('Snapshot');
|
||||
expect(input).toBeTruthy();
|
||||
expect(input?.value).toBe('Snapshot');
|
||||
expect(mirror.textContent).toBe('Snapshot');
|
||||
expect(input).toHaveValue('Snapshot');
|
||||
|
||||
// width should be set inline (component calculates width on mount)
|
||||
expect(input?.getAttribute('style')).toContain('width:');
|
||||
expect(input.getAttribute('style')).toContain('width:');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,7 +49,12 @@ function OverflowInputToolTip({
|
||||
|
||||
return (
|
||||
<>
|
||||
<span ref={mirrorRef} aria-hidden className="overflow-input-mirror" />
|
||||
<span
|
||||
ref={mirrorRef}
|
||||
aria-hidden
|
||||
className="overflow-input-mirror"
|
||||
data-testid="overflow-input-mirror"
|
||||
/>
|
||||
<Tooltip title={tooltipTitle} placement={tooltipPlacement}>
|
||||
<Input
|
||||
{...rest}
|
||||
|
||||
@@ -273,7 +273,10 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
)}
|
||||
|
||||
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
<div
|
||||
className="qb-formulas-container"
|
||||
data-testid="qb-formulas-container"
|
||||
>
|
||||
{activeBuilder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
activeBuilder.queryData[index] || activeBuilder.queryData[0];
|
||||
@@ -312,7 +315,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
</div>
|
||||
|
||||
{showQueryList && (
|
||||
<div className="query-names-section">
|
||||
<div className="query-names-section" data-testid="query-names-section">
|
||||
{renderedQueries.map((query) => (
|
||||
<div key={query.queryName} className="query-name">
|
||||
{query.queryName}
|
||||
|
||||
@@ -106,8 +106,10 @@ function QueryAddOns({
|
||||
|
||||
if (
|
||||
panelType === PANEL_TYPES.HEATMAP &&
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
!HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
!(
|
||||
query.dataSource === DataSource.METRICS &&
|
||||
HISTOGRAM_ATTRIBUTE_TYPES.has(query.aggregateAttribute?.type ?? '')
|
||||
)
|
||||
) {
|
||||
addOns = [...addOns, BUCKET_OPTIONS];
|
||||
}
|
||||
@@ -436,6 +438,7 @@ function QueryAddOns({
|
||||
onChange={handleChangeOrderByKeys}
|
||||
isRawQuery={isRawQuery}
|
||||
isNewQueryV2
|
||||
panelType={panelType ?? undefined}
|
||||
placeholder={placeholderOf(QueryBuilderField.OrderBy)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -107,8 +107,8 @@ export const BASE_ADD_ONS = (
|
||||
|
||||
export const REDUCE_TO = toAddOn(QueryBuilderField.ReduceTo);
|
||||
|
||||
// Offered only by a heatmap over metrics: the bucket axis is what a heatmap plots
|
||||
// against, and no other panel type sends one. A histogram brings its own buckets.
|
||||
// Offered only by a heatmap: the bucket axis is what a heatmap plots against, and no
|
||||
// other panel type sends one. A histogram metric brings its own buckets.
|
||||
export const HISTOGRAM_ATTRIBUTE_TYPES = new Set<string>([
|
||||
ATTRIBUTE_TYPES.HISTOGRAM,
|
||||
ATTRIBUTE_TYPES.EXPONENTIAL_HISTOGRAM,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// Fills the row like the filter and Group By boxes.
|
||||
.select {
|
||||
flex: 1;
|
||||
min-width: 400px;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Combobox } from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { getDistributionFieldPlaceholder } from 'lib/query/distributionField';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DATA_SOURCE_TO_SIGNAL } from 'types/common/queryBuilder';
|
||||
|
||||
import { toDistributionFieldOptions } from './distributionFieldOptions';
|
||||
|
||||
import Styles from './DistributionFieldSelect.module.scss';
|
||||
|
||||
/** A logs or traces heatmap's aggregation: the one numeric field it buckets. */
|
||||
export default function DistributionFieldSelect({
|
||||
queryData,
|
||||
onChange,
|
||||
}: {
|
||||
queryData: IBuilderQuery;
|
||||
onChange?: (field: string) => void;
|
||||
}): JSX.Element {
|
||||
const [search, setSearch] = useState('');
|
||||
const searchText = useDebounce(search, DEBOUNCE_DELAY);
|
||||
|
||||
// The keys API caps its answer, so a field past the cap is reached by searching.
|
||||
const {
|
||||
data: fieldKeys,
|
||||
isLoading,
|
||||
isFetching,
|
||||
} = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
|
||||
searchText,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.number,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
{ keepPreviousData: true },
|
||||
);
|
||||
|
||||
const [aggregation] = queryData.aggregations ?? [];
|
||||
const selectedField =
|
||||
aggregation && 'expression' in aggregation ? aggregation.expression : '';
|
||||
|
||||
const items = useMemo(
|
||||
() => toDistributionFieldOptions(fieldKeys ?? [], selectedField),
|
||||
[fieldKeys, selectedField],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={Styles.select}>
|
||||
<Combobox
|
||||
items={items}
|
||||
value={selectedField || undefined}
|
||||
onChange={(field): void => onChange?.(field ?? '')}
|
||||
allowClear
|
||||
placeholder={getDistributionFieldPlaceholder(queryData.dataSource)}
|
||||
searchInputProps={{
|
||||
placeholder: 'Search numeric fields',
|
||||
loading: isFetching,
|
||||
onChange: setSearch,
|
||||
}}
|
||||
loading={isLoading}
|
||||
noContent="No numeric fields"
|
||||
testId="distribution-field-select"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
IBuilderQuery,
|
||||
IBuilderTraceOperator,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { aggregatesDistributionField } from 'lib/query/distributionField';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import {
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
} from '../../queryBuilderFields.utils';
|
||||
|
||||
import { isScalarPanelType } from '../panelTypes';
|
||||
import DistributionFieldSelect from './DistributionFieldSelect';
|
||||
import QueryAggregationSelect from './QueryAggregationSelect';
|
||||
|
||||
import './QueryAggregation.styles.scss';
|
||||
@@ -63,17 +65,21 @@ function QueryAggregationOptions({
|
||||
data-testid="query-aggregation-container"
|
||||
>
|
||||
<div className="aggregation-container">
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{aggregatesDistributionField(panelType, dataSource) ? (
|
||||
<DistributionFieldSelect queryData={queryData} onChange={onChange} />
|
||||
) : (
|
||||
<QueryAggregationSelect
|
||||
onChange={onChange}
|
||||
queryData={queryData}
|
||||
maxAggregations={
|
||||
panelType === PANEL_TYPES.VALUE ||
|
||||
panelType === PANEL_TYPES.PIE ||
|
||||
panelType === PANEL_TYPES.TOP_LIST
|
||||
? 1
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!stepInterval.hidden && (
|
||||
<div className="query-aggregation-interval">
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import {
|
||||
TelemetrytypesFieldContextDTO,
|
||||
TelemetrytypesFieldDataTypeDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
type GetFieldsKeys200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import DistributionFieldSelect from '../DistributionFieldSelect';
|
||||
|
||||
const keysResponse: GetFieldsKeys200 = {
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
keys: {
|
||||
duration_nano: [
|
||||
{
|
||||
name: 'duration_nano',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.span,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
quantity: [
|
||||
{
|
||||
name: 'quantity',
|
||||
fieldContext: TelemetrytypesFieldContextDTO.attribute,
|
||||
fieldDataType: TelemetrytypesFieldDataTypeDTO.float64,
|
||||
signal: TelemetrytypesSignalDTO.traces,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const tracesQuery = (expression: string): IBuilderQuery => ({
|
||||
...(initialQueriesMap.traces.builder.queryData[0] as IBuilderQuery),
|
||||
aggregations: [{ expression }],
|
||||
});
|
||||
|
||||
describe('DistributionFieldSelect', () => {
|
||||
const requests: URLSearchParams[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
server.use(
|
||||
rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (req, res, ctx) => {
|
||||
requests.push(req.url.searchParams);
|
||||
return res(ctx.status(200), ctx.json(keysResponse));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the saved field', () => {
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('distribution-field-select')).toHaveTextContent(
|
||||
'duration_nano',
|
||||
);
|
||||
});
|
||||
|
||||
it('picks a numeric field, keeping its context', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
expect(requests[0].get('fieldDataType')).toBe(
|
||||
TelemetrytypesFieldDataTypeDTO.number,
|
||||
);
|
||||
expect(requests[0].get('signal')).toBe('traces');
|
||||
});
|
||||
|
||||
it('replaces the saved field with the newly picked one', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
queryData={tracesQuery('duration_nano')}
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'attribute.quantity{Enter}',
|
||||
);
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith('attribute.quantity');
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await screen.findByTestId(
|
||||
'distribution-field-select-item-attribute.quantity',
|
||||
);
|
||||
await user.type(
|
||||
screen.getByTestId('distribution-field-select-search'),
|
||||
'no_such_field',
|
||||
);
|
||||
|
||||
await screen.findByText('No numeric fields');
|
||||
expect(
|
||||
screen.queryByTestId('distribution-field-select-item-no_such_field'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('searches the server for typed text, past the listed fields', async () => {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
pointerEventsCheck: 0,
|
||||
});
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('distribution-field-select'));
|
||||
await user.type(
|
||||
await screen.findByTestId('distribution-field-select-search'),
|
||||
'queue',
|
||||
);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(DEBOUNCE_DELAY);
|
||||
});
|
||||
|
||||
await waitFor(() => expect(requests.at(-1)?.get('searchText')).toBe('queue'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
toDistributionFieldOptions,
|
||||
toDistributionFieldText,
|
||||
} from '../distributionFieldOptions';
|
||||
|
||||
const key = (
|
||||
name: string,
|
||||
fieldContext: FieldContext,
|
||||
): { name: string; fieldContext: FieldContext } => ({ name, fieldContext });
|
||||
|
||||
const KEYS = [
|
||||
key('quantity', FieldContext.resource),
|
||||
key('duration_nano', FieldContext.span),
|
||||
key('quantity', FieldContext.attribute),
|
||||
key('total_tokens', FieldContext.trace),
|
||||
key('latency', FieldContext.body),
|
||||
key('duration_nano', FieldContext.span),
|
||||
];
|
||||
|
||||
describe('toDistributionFieldText', () => {
|
||||
it.each([
|
||||
[key('duration_nano', FieldContext.span), 'duration_nano'],
|
||||
[key('severity_number', FieldContext.log), 'severity_number'],
|
||||
[
|
||||
key('http.status_code', FieldContext.attribute),
|
||||
'attribute.http.status_code',
|
||||
],
|
||||
[key('latency', FieldContext.body), 'body.latency'],
|
||||
])('%j → %s', (fieldKey, text) => {
|
||||
expect(toDistributionFieldText(fieldKey)).toBe(text);
|
||||
});
|
||||
});
|
||||
|
||||
const item = (
|
||||
text: string,
|
||||
): { type: 'item'; label: string; value: string } => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
describe('toDistributionFieldOptions', () => {
|
||||
it('groups columns first, keeps contexts apart, drops trace keys and repeats', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, 'duration_nano')).toStrictEqual([
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Columns',
|
||||
value: 'column',
|
||||
items: [item('duration_nano')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Attribute',
|
||||
value: 'attribute',
|
||||
items: [item('attribute.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Resource',
|
||||
value: 'resource',
|
||||
items: [item('resource.quantity')],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: 'Body',
|
||||
value: 'body',
|
||||
items: [item('body.latency')],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leads with a saved field the keys do not carry', () => {
|
||||
const options = toDistributionFieldOptions(KEYS, 'queue-depth');
|
||||
expect(options[0]).toStrictEqual(item('queue-depth'));
|
||||
expect(options).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('adds nothing for an empty or listed field', () => {
|
||||
expect(toDistributionFieldOptions(KEYS, '')).toHaveLength(4);
|
||||
expect(toDistributionFieldOptions(KEYS, 'body.latency')).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type {
|
||||
ComboboxItemType,
|
||||
ComboboxOptionItemType,
|
||||
} from '@signozhq/ui/combobox';
|
||||
import { TelemetrytypesFieldContextDTO as FieldContext } from 'api/generated/services/sigNoz.schemas';
|
||||
import { upperFirst } from 'lodash-es';
|
||||
import type { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
|
||||
// Span and log columns are read by their name alone; anything else keeps its
|
||||
// context so `attribute.quantity` and `resource.quantity` stay apart.
|
||||
const COLUMN_CONTEXTS = new Set<string | undefined>([
|
||||
FieldContext.span,
|
||||
FieldContext.log,
|
||||
FieldContext[''],
|
||||
]);
|
||||
|
||||
const GROUP_ORDER: string[] = [
|
||||
'column',
|
||||
FieldContext.attribute,
|
||||
FieldContext.resource,
|
||||
];
|
||||
|
||||
const headingOf = (group: string): string =>
|
||||
group === 'column' ? 'Columns' : upperFirst(group);
|
||||
|
||||
const toItem = (text: string): ComboboxOptionItemType => ({
|
||||
type: 'item',
|
||||
label: text,
|
||||
value: text,
|
||||
});
|
||||
|
||||
/** The key text the querier parses back into this key (`GetFieldKeyFromKeyText`). */
|
||||
export function toDistributionFieldText(key: TelemetryFieldKey): string {
|
||||
return COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? key.name
|
||||
: `${key.fieldContext}.${key.name}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numeric keys grouped by context, each one once. `trace.*` keys are per-trace
|
||||
* aggregates, which a heatmap cannot bucket. A saved field the keys do not carry
|
||||
* leads as its own item, so the combobox can still show it.
|
||||
*/
|
||||
export function toDistributionFieldOptions(
|
||||
keys: TelemetryFieldKey[],
|
||||
selectedField: string,
|
||||
): ComboboxItemType[] {
|
||||
const byGroup = new Map<string, Set<string>>();
|
||||
keys
|
||||
.filter((key) => key.fieldContext !== FieldContext.trace)
|
||||
.forEach((key) => {
|
||||
const group = COLUMN_CONTEXTS.has(key.fieldContext)
|
||||
? 'column'
|
||||
: String(key.fieldContext);
|
||||
byGroup.set(
|
||||
group,
|
||||
(byGroup.get(group) ?? new Set()).add(toDistributionFieldText(key)),
|
||||
);
|
||||
});
|
||||
|
||||
const isSelectedListed = [...byGroup.values()].some((texts) =>
|
||||
texts.has(selectedField),
|
||||
);
|
||||
const rank = (group: string): number => {
|
||||
const index = GROUP_ORDER.indexOf(group);
|
||||
return index === -1 ? GROUP_ORDER.length : index;
|
||||
};
|
||||
|
||||
const groups = [...byGroup.entries()]
|
||||
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
|
||||
.map(([group, texts]): ComboboxItemType => ({
|
||||
type: 'group',
|
||||
label: headingOf(group),
|
||||
value: group,
|
||||
items: [...texts].map(toItem),
|
||||
}));
|
||||
|
||||
return selectedField && !isSelectedListed
|
||||
? [toItem(selectedField), ...groups]
|
||||
: groups;
|
||||
}
|
||||
@@ -317,23 +317,20 @@ function QuerySearch({
|
||||
500,
|
||||
);
|
||||
|
||||
const toggleSuggestions = useCallback(
|
||||
(timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (isFocused) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
const toggleSuggestions = useCallback((timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (editorRef.current.hasFocus) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
},
|
||||
[isFocused],
|
||||
);
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
}, []);
|
||||
|
||||
const fetchKeySuggestions = useCallback(
|
||||
async (searchText?: string): Promise<void> => {
|
||||
@@ -1597,7 +1594,10 @@ function QuerySearch({
|
||||
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
|
||||
{isScopedFilter && !showScopeChip ? (
|
||||
<Tooltip title={initialExpression || ''} placement="left">
|
||||
<div className="query-search-initial-scope-label">
|
||||
<div
|
||||
className="query-search-initial-scope-label"
|
||||
data-testid="query-search-initial-scope-label"
|
||||
>
|
||||
<Filter
|
||||
size={14}
|
||||
style={{
|
||||
|
||||
@@ -168,6 +168,7 @@ export function renderRecentDeleteButton(
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'cm-recent-delete';
|
||||
btn.dataset.testid = 'query-search-recent-delete';
|
||||
btn.setAttribute('aria-label', 'Remove from recent searches');
|
||||
btn.title = 'Remove from recent searches';
|
||||
btn.textContent = '×';
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
@@ -19,6 +19,7 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
|
||||
const EDITOR_TEST_ID = 'query-aggregation-editor';
|
||||
// CodeMirror's suggestion popup is slow to open under a parallel jest run.
|
||||
@@ -116,7 +117,7 @@ async function enterAggregation(
|
||||
queryData: IBuilderQuery = aiQuery,
|
||||
currentQuery?: Query,
|
||||
): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryAggregationSelect queryData={queryData} />
|
||||
@@ -125,12 +126,9 @@ async function enterAggregation(
|
||||
{ queryBuilderOverrides: currentQuery && { currentQuery } },
|
||||
);
|
||||
|
||||
const content = (
|
||||
await screen.findByTestId(EDITOR_TEST_ID)
|
||||
).querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('CodeMirror content element not rendered');
|
||||
}
|
||||
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
|
||||
'textbox',
|
||||
);
|
||||
await user.click(content);
|
||||
// Typed keys drop under load: a re-render's dispatch discards DOM input CodeMirror hasn't read yet.
|
||||
await user.paste(text);
|
||||
@@ -138,10 +136,10 @@ async function enterAggregation(
|
||||
}
|
||||
|
||||
function suggestionLabels(): string[] {
|
||||
return Array.from(
|
||||
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
|
||||
(label) => label.textContent ?? '',
|
||||
).sort();
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((option) => option.textContent ?? '')
|
||||
.sort();
|
||||
}
|
||||
|
||||
describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
@@ -161,9 +159,10 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
async ({ aggregation, fieldDataType, labels }) => {
|
||||
await enterAggregation(aggregation);
|
||||
|
||||
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual(labels);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
expect(
|
||||
aiKeysRequests.map((params) => ({
|
||||
@@ -185,14 +184,13 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]),
|
||||
{ timeout: SUGGESTIONS_TIMEOUT_MS },
|
||||
);
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
beforeAll(() => {
|
||||
mockCodeMirrorDomApis();
|
||||
@@ -110,11 +111,7 @@ async function renderAndType(text: string): Promise<HTMLElement> {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, text);
|
||||
return editor;
|
||||
@@ -128,32 +125,26 @@ async function typeKeyThenEnterOperatorContext(
|
||||
): Promise<void> {
|
||||
const editor = await renderAndType(key);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain(expectedKeyLabel);
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
|
||||
|
||||
// skipClick: a click would reset the caret to position 0 under the mocked
|
||||
// DOM rects; we need the space appended at the end of the typed key.
|
||||
await userEvent.type(editor, ' ', { skipClick: true });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('=');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, '=');
|
||||
}
|
||||
|
||||
function visibleOptionLabels(): string[] {
|
||||
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(
|
||||
(el) => el.textContent ?? '',
|
||||
);
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((el) => el.textContent ?? '');
|
||||
}
|
||||
|
||||
describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows one deduped suggestion per key name in normal mode', async () => {
|
||||
await renderAndType('statu');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'status.code');
|
||||
|
||||
const statusOptions = visibleOptionLabels().filter(
|
||||
(label) => label === 'status.code',
|
||||
@@ -164,9 +155,7 @@ describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows context-scoped suggestions for a complete context prefix', async () => {
|
||||
await renderAndType('attribute.');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('attribute.status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
|
||||
|
||||
const labels = visibleOptionLabels();
|
||||
// Literal key name match ranks first
|
||||
|
||||
@@ -2,7 +2,9 @@ import { EditorView } from '@uiw/react-codemirror';
|
||||
import { getFieldKeySuggestions } from 'api/querySuggestions/getFieldKeySuggestions';
|
||||
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
@@ -14,8 +16,9 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
// Mock DOM APIs that CodeMirror needs
|
||||
beforeAll(() => {
|
||||
@@ -75,8 +78,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// CodeMirror renders a contenteditable div, so we check for the container
|
||||
const editorContainer = document.querySelector('.query-where-clause-editor');
|
||||
expect(editorContainer).toBeInTheDocument();
|
||||
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches key suggestions when typing a key (debounced)', async () => {
|
||||
@@ -94,14 +96,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find the CodeMirror editor contenteditable element
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
|
||||
// Focus and type into the editor
|
||||
await userEvent.click(editor);
|
||||
@@ -141,12 +137,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
|
||||
|
||||
@@ -162,6 +153,49 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
await expect(screen.findByText('200')).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the value suggestions open when the key suggestions load', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { held, release } = holdResponse();
|
||||
const mockedGetKeys = jest.mocked(getFieldKeySuggestions);
|
||||
mockedGetKeys.mockClear();
|
||||
mockedGetKeys.mockImplementationOnce(async () => {
|
||||
await held;
|
||||
return { status: 'success', data: { complete: true, keys: {} } };
|
||||
});
|
||||
jest.mocked(getFieldValueSuggestions).mockResolvedValueOnce({
|
||||
status: 'success',
|
||||
data: {
|
||||
complete: true,
|
||||
values: {
|
||||
stringValues: ['payment-service'],
|
||||
numberValues: [],
|
||||
boolValues: [],
|
||||
relatedValues: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn()}
|
||||
queryData={initialQueriesMap.logs.builder.queryData[0]}
|
||||
dataSource={DataSource.LOGS}
|
||||
/>,
|
||||
);
|
||||
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await user.click(editor);
|
||||
await user.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
|
||||
await screen.findByText('payment-service');
|
||||
await waitFor(() => expect(mockedGetKeys).toHaveBeenCalled());
|
||||
|
||||
release();
|
||||
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
|
||||
expect(screen.getByText('payment-service')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches key suggestions on mount for LOGS', async () => {
|
||||
// Use real timers for CodeMirror integration tests
|
||||
const mockedGetKeysOnMount = getFieldKeySuggestions as jest.MockedFunction<
|
||||
@@ -203,12 +237,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
|
||||
|
||||
@@ -255,11 +284,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -268,7 +294,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
|
||||
it('shows the locked scope as a chip in place of the scope icon', () => {
|
||||
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -283,12 +309,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
expect(chip).toHaveTextContent('+1');
|
||||
expect(chip).not.toHaveTextContent('kind_string');
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.queryByTestId('query-search-initial-scope-label'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the scope icon unless the chip is asked for', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -301,7 +327,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
screen.queryByTestId('query-search-scope-chip'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.getByTestId('query-search-initial-scope-label'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -341,11 +367,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -371,13 +394,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize and the expression to be set
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
// CodeMirror stores content in .cm-content, check the text content
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
// CodeMirror may render the text in multiple ways, check if it contains our expression
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toContain('http.status_code');
|
||||
@@ -412,12 +431,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize with the initial expression
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toBe(initialExpression);
|
||||
},
|
||||
@@ -477,11 +493,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent.textContent || '').toBe(initialExpression);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user