Compare commits

..

6 Commits

639 changed files with 5357 additions and 15412 deletions

View File

@@ -9,7 +9,7 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.

View File

@@ -10,6 +10,5 @@
- **Use convensional commit format** for commits and PR title.
- **Do not amend the commits once pushed.** Always create a new commit once changes are pushed to remote.
- **Review fixes are new commits too.** A force push hides what changed from human reviewers and makes Greptile post its findings again. Bring in `main` with a merge; only a stacked branch (`gh stack`) rebases, since the stack moves as a unit.
- **A review fix to an AI-owned file fixes its generator too.** A file with the AI-owned banner (story mocks and plays, `tests/e2e/drivers/`) is rewritten by the skill or agent that made it, so a fix made only in the file comes back on the next run. In the same PR, add the lesson to that skill or agent as a concrete case.
- **Answer every Greptile thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve one with neither: Greptile withdraws a finding, and remembers it, only when told why.
- **Leave human review threads to the author.** Fix the code they ask for, but never reply to or resolve a human reviewer's thread.

View File

@@ -110,9 +110,8 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
Before writing the clicks, list what has to be on screen for the play's target to exist. Then walk every control the story exposes, the page's own as well as the shared ones, and return early for each value that takes something on that list away. These are the cases plays have missed:
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
- A view, filter or invalid query that leaves no rows, even when the count is above 0.

View File

@@ -184,6 +184,22 @@ jobs:
name: playwright-artifacts-${{ matrix.project }}-${{ matrix.shard }}
path: tests/e2e/artifacts/
retention-days: 5
- name: find-flaky
id: flaky
if: always()
run: |
results=tests/e2e/artifacts/json/results.json
if [ -f "$results" ] && [ "$(jq '.stats.flaky' "$results")" -gt 0 ]; then
echo "found=true" >> "$GITHUB_OUTPUT"
fi
# The weekly flakyci report reads these; the window is 7 days.
- name: upload-flaky
if: always() && steps.flaky.outputs.found == 'true'
uses: actions/upload-artifact@v4
with:
name: e2e-flaky-${{ matrix.project }}-${{ matrix.shard }}
path: tests/e2e/artifacts/json/results.json
retention-days: 8
# Required status check. Fails when e2e was needed but did not pass.
e2e:
# Runs for other labels must not report as e2e, or their pass would hide the real result.

26
.github/workflows/flakyci.yaml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: flakyci
on:
schedule:
- cron: "0 4 * * 1"
workflow_dispatch:
permissions:
actions: read
contents: read
jobs:
flaky-tests:
runs-on: ubuntu-latest
steps:
- name: self-checkout
uses: actions/checkout@v4
- name: node-install
uses: actions/setup-node@v5
with:
node-version: "22"
- name: report
env:
GH_TOKEN: ${{ github.token }}
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_FLAKY_TESTS_WEBHOOK }}
run: node frontend/scripts/flaky-test-report.mjs >> "$GITHUB_STEP_SUMMARY"

View File

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

View File

@@ -131,10 +131,6 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionKey).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
}
allowedTypes := map[string]bool{}

View File

@@ -296,8 +296,6 @@
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
"signoz/no-direct-react-router-import": "error",
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
"signoz/no-builder-ai-query-access": "error",
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -318,11 +316,6 @@
"name": "redux",
"message": "[State mgmt] redux is deprecated. Migrate to Zustand, nuqs, or react-query."
},
{
"name": "@signozhq/design-tokens",
"importNames": ["Style"],
"message": "[bundle] Style is a large object of CSS variable strings and is not tree-shaken. Write the CSS variable directly, for example 'var(--l3-foreground)'."
},
{
"name": "react-redux",
"message": "[State mgmt] react-redux is deprecated. Migrate to Zustand, nuqs, or react-query."
@@ -345,11 +338,6 @@
"importNames": ["patchDashboardV2", "usePatchDashboardV2"],
"message": "[dashboard-v2] Don't call patchDashboardV2/usePatchDashboardV2 directly — use useOptimisticPatch().patchAsync so spec edits update the react-query cache optimistically and reconcile on settle."
},
{
"name": "antd/lib",
"allowTypeImports": true,
"message": "[bundle] antd/lib is the CommonJS root and bundles every antd component. Import from 'antd' instead."
},
{
"name": "motion/react-client",
"message": "[motion] motion/react-client is for React Server Components only. Use 'motion/react' instead — it provides the same exports and works correctly in client-side SPAs."
@@ -564,7 +552,6 @@
],
"rules": {
"import/first": "off",
"signoz/no-dom-node-access": "error",
// Should ignore due to mocks
"signoz/no-navigator-clipboard": "off",
// Tests can use navigator.clipboard directly,
@@ -572,8 +559,6 @@
"no-restricted-globals": "off",
// Tests need raw localStorage/sessionStorage to seed DOM state for isolation
"signoz/no-zustand-getstate-in-hooks": "off",
"signoz/no-builder-ai-query-access": "off",
// Fixtures build and assert on the raw AI slot
"@typescript-eslint/no-explicit-any": "off", // Tests often need any for mocks/stubs
"@typescript-eslint/explicit-module-boundary-types": "off", // Return types not required in tests
"@typescript-eslint/explicit-function-return-type": "off" // Same as above rule, don't need to care about return type
@@ -630,20 +615,6 @@
"rules": {
"signoz/no-direct-react-router-import": "off"
}
},
{
// builderSlot owns the AI slot; the rest normalise its wire shape or test whether it exists, which the helpers hide
"files": [
"src/lib/query/builderSlot.ts",
"src/hooks/queryBuilder/normalizeCompositeQuery.ts",
"src/hooks/queryBuilder/useGetCompositeQueryParam.ts",
"src/providers/QueryBuilder.tsx",
"src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelKindChange.ts",
"src/pages/DashboardPage/DashboardContainer/Panels/utils/seedBuilderForMode.ts"
],
"rules": {
"signoz/no-builder-ai-query-access": "off"
}
}
]
}

View File

@@ -15,6 +15,8 @@
content="frame-src 'self' blob: data:"
/>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script>
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
// /public/locales does not ship; pin it to the bundled language instead.

View File

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

View File

@@ -157,6 +157,7 @@
})(document, 'script');
}
</script>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

View File

@@ -11,9 +11,9 @@ const config: Config.InitialOptions = {
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
modulePathIgnorePatterns: ['dist'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff|wav)$':
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'<rootDir>/__mocks__/fileMock.ts',
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.
@@ -69,6 +69,9 @@ const config: Config.InitialOptions = {
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' }),
...(process.env.GITHUB_STEP_SUMMARY
? { reporters: ['default', '<rootDir>/scripts/slow-test-reporter.mjs'] }
: {}),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -57,7 +57,7 @@
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/ui": "0.4.1-rc.2",
"@signozhq/ui": "0.4.0-rc.5",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

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

View File

@@ -1,60 +0,0 @@
import { ruleTester } from './rule-tester.mjs';
const message = (name) =>
`Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`;
await ruleTester({
rule: 'no-dom-node-access',
valid: [
{
name: 'Testing Library queries',
code: "within(screen.getByTestId('row')).getByText('Name');",
},
{
name: 'a query method that is not called',
code:
'jest.spyOn(document, "querySelector");\nconst q = Element.prototype.closest;',
},
{
name: 'computed access',
code: "const name = 'closest';\nel[name]('tr');",
},
],
invalid: [
{
name: 'querySelector on the container',
code: "container.querySelector('.row');",
errors: [{ message: message('querySelector'), line: 1, column: 11 }],
},
{
name: 'closest after a screen query',
code: "screen.getByText('Name').closest('tr');",
errors: [{ message: message('closest'), line: 1, column: 26 }],
},
{
name: 'optional call',
code: "row?.querySelectorAll('td');",
errors: [{ message: message('querySelectorAll'), line: 1, column: 6 }],
},
{
name: 'traversal property',
code: 'expect(cell.parentElement).toBeVisible();',
errors: [{ message: message('parentElement'), line: 1, column: 13 }],
},
{
name: 'children of a DOM node',
code: "expect(screen.getByTestId('list').children).toHaveLength(2);",
errors: [{ message: message('children'), line: 1, column: 35 }],
},
{
name: 'children of a data tree',
code: 'expect(tree.children).toHaveLength(2);',
errors: [{ message: message('children'), line: 1, column: 13 }],
},
{
name: 'document lookup by id',
code: "document.getElementById('root');",
errors: [{ message: message('getElementById'), line: 1, column: 10 }],
},
],
});

View File

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

View File

@@ -1,60 +0,0 @@
/**
* Rule: no-dom-node-access
*
* Tests find elements through Testing Library (`screen`, `within`), not by
* walking the DOM. Flags calls to DOM query methods and reads of node
* traversal properties:
* container.querySelector('.row')
* screen.getByText('Name').closest('tr')
* cell.parentElement
* list.children
*
* A non-DOM `children` read (a data tree, React props) disables the rule on
* that line with a reason.
*/
const QUERY_METHODS = new Set([
'querySelector',
'querySelectorAll',
'closest',
'getElementById',
'getElementsByClassName',
'getElementsByTagName',
'getElementsByName',
]);
const TRAVERSAL_PROPERTIES = new Set([
'parentElement',
'parentNode',
'firstChild',
'lastChild',
'firstElementChild',
'lastElementChild',
'nextSibling',
'previousSibling',
'nextElementSibling',
'previousElementSibling',
'childNodes',
'children',
]);
export default {
create(context) {
return {
MemberExpression(node) {
if (node.computed || node.property.type !== 'Identifier') {
return;
}
const { name } = node.property;
const isCall =
node.parent?.type === 'CallExpression' && node.parent.callee === node;
if ((isCall && QUERY_METHODS.has(name)) || TRAVERSAL_PROPERTIES.has(name)) {
context.report({
node: node.property,
message: `Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`,
});
}
},
};
},
};

View File

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

View File

@@ -86,8 +86,8 @@ importers:
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.1-rc.2
version: 0.4.1-rc.2(@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)
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)
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3258,8 +3258,8 @@ packages:
react: ^18.2.0
react-query: ^3.39.3
'@signozhq/ui@0.4.1-rc.2':
resolution: {integrity: sha512-pCMRzrJ6CmGjEgAQ2B6wRRengP2sy7Y860Npr5nkCapc9NPH5jy4VO48CDv5gnKwWSKShmLHwzbiK2E1cGndKQ==}
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
peerDependencies:
'@signozhq/design-tokens': '>=2.7.0'
'@signozhq/icons': 0.3.0
@@ -12389,7 +12389,7 @@ snapshots:
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.1-rc.2(@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)':
'@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)
'@signozhq/design-tokens': 2.8.0

1
frontend/public/css/uPlot.min.css vendored Normal file
View File

@@ -0,0 +1 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}

View File

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

View File

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

View File

@@ -0,0 +1,245 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { slackMessages } from '../flaky-test-format.mjs';
import { findFlaky, prOf } from '../flaky-test-report.mjs';
import { rateLimitWait } from '../github-api.mjs';
import {
parseJest,
parsePlaywright,
parsePlaywrightReport,
} from '../test-log-parsers.mjs';
const JEST_LOG = [
'2026-11-10T10:00:00.0000000Z \x1b[1mFAIL\x1b[22m src/a/A.test.tsx (12.1 s)',
'2026-11-10T10:00:00.0000001Z \x1b[1m● A › saves the form\x1b[22m',
'2026-11-10T10:00:00.0000002Z ',
'2026-11-10T10:00:00.0000003Z thrown: "Exceeded timeout of 5000 ms for a test.',
'2026-11-10T10:00:00.0000004Z FAIL src/b/B.test.tsx',
'2026-11-10T10:00:00.0000005Z ● B › shows the error',
'2026-11-10T10:00:00.0000006Z expect(received).toBe(expected)',
'2026-11-10T10:00:00.0000007Z ● Test suite failed to run',
'2026-11-10T10:00:00.0000008Z FAIL src/a/A.test.tsx (12.1 s)',
'2026-11-10T10:00:00.0000009Z ● A › saves the form',
].join('\n');
const STORYBOOK_LOG = [
'2026-11-24T14:52:01.9166715Z \x1b[0m\x1b[7m\x1b[1m\x1b[31m FAIL \x1b[39m\x1b[22m\x1b[27m\x1b[0m \x1b[0m\x1b[7m\x1b[33m browser: chromium \x1b[39m\x1b[27m\x1b[0m \x1b[2msrc/q/stories/\x1b[22m\x1b[1mQ.stories.tsx\x1b[22m (\x1b[0m',
'2026-11-24T14:52:01.9168486Z \x1b[1m\x1b[31m \x1b[1m● \x1b[22m\x1b[1mComponents/Q › WhereClauseSuggestions › play-test\x1b[39m\x1b[22m',
'2026-11-24T14:52:01.9168487Z [error] AssertionError: expected 0 to be greater than 0',
'2026-11-24T14:54:46.4233854Z \x1b[0m\x1b[7m\x1b[1m\x1b[31m FAIL \x1b[39m\x1b[22m\x1b[27m\x1b[0m \x1b[2mfrontend/src/q/stories/\x1b[22m\x1b[1mQ.stories.tsx\x1b[22m (34.267 s)',
'2026-11-24T14:54:46.4236531Z \x1b[1m\x1b[31m \x1b[1m● \x1b[22m\x1b[1mComponents/Q › WhereClauseSuggestions › play-test\x1b[39m\x1b[22m',
].join('\n');
const PLAYWRIGHT_LOG = [
'2026-11-24T17:12:13.5413743Z ✓ 55 [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render (retry #1) (18.3s)',
'2026-11-24T17:15:01.8981922Z 1) [chromium] › tests/s/list.spec.ts:32:6 › Services, list › TC-02 opens the overview ',
'2026-11-24T17:15:01.8982565Z ',
'2026-11-24T17:15:01.8982929Z Error: \x1b[2mexpect(\x1b[22mreceived).toEqual(expected) // deep equality',
'2026-11-24T17:15:01.9025205Z 2) [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render ',
'2026-11-24T17:15:01.9025206Z Error: locator.click: Timeout 15000ms exceeded.',
'2026-11-24T17:15:01.9032403Z 1 failed',
'2026-11-24T17:15:01.9032812Z [chromium] › tests/s/list.spec.ts:32:6 › Services, list › TC-02 opens the overview ',
'2026-11-24T17:15:01.9033155Z 1 flaky',
'2026-11-24T17:15:01.9033637Z [chromium] › tests/s/detail.spec.ts:70:6 › Services, detail › TC-04 tabs render ',
'2026-11-24T17:15:01.9034012Z 77 passed (7.4m)',
].join('\n');
const JEST = { name: 'Jest', root: 'frontend/' };
const E2E = { name: 'E2E', root: 'tests/e2e/' };
test('parseJest reads each failing test once with its first error line', () => {
assert.deepEqual(parseJest(JEST_LOG), [
{
file: 'src/a/A.test.tsx',
test: 'A › saves the form',
error: 'thrown: "Exceeded timeout of 5000 ms for a test.',
retried: false,
},
{
file: 'src/b/B.test.tsx',
test: 'B › shows the error',
error: 'expect(received).toBe(expected)',
retried: false,
},
]);
});
test('parseJest reads the storybook runner file under both of its prefixes', () => {
assert.deepEqual(parseJest(STORYBOOK_LOG), [
{
file: 'src/q/stories/Q.stories.tsx',
test: 'Components/Q › WhereClauseSuggestions › play-test',
error: '[error] AssertionError: expected 0 to be greater than 0',
retried: false,
},
]);
});
test('parsePlaywright reads the tests that failed every retry', () => {
assert.deepEqual(parsePlaywright(PLAYWRIGHT_LOG), [
{
file: 'tests/s/list.spec.ts',
test: 'Services, list › TC-02 opens the overview',
error: 'Error: expect(received).toEqual(expected) // deep equality',
retried: false,
},
]);
});
test('parsePlaywrightReport reads the tests that passed on a retry', () => {
const spec = (title, status, error) => ({
title,
file: 's/detail.spec.ts',
tests: [
{
status,
results: [
{ status: 'failed', ...(error && { error: { message: error } }) },
],
},
],
});
const report = {
config: { rootDir: '/home/runner/work/signoz/signoz/tests/e2e/tests' },
suites: [
{
title: 's/detail.spec.ts',
specs: [spec('TC-01 loads', 'expected')],
suites: [
{
title: 'Services, detail',
specs: [
spec(
'TC-04 tabs render',
'flaky',
'Error: \x1b[2mlocator.click\x1b[22m: Timeout\n at detail.spec.ts:70',
),
spec('TC-05 failed every retry', 'unexpected', 'Error: nope'),
],
},
],
},
],
};
assert.deepEqual(parsePlaywrightReport(report), [
{
file: 'tests/s/detail.spec.ts',
test: 'Services, detail › TC-04 tabs render',
error: 'Error: locator.click: Timeout',
retried: true,
},
]);
});
test('findFlaky keeps retry, re-run and multi-PR failures only', () => {
const failure = (test, extra) => ({
suite: JEST,
file: 'src/x.test.tsx',
test,
error: '',
retried: false,
event: 'pull_request',
pr: 1,
passedOnRerun: false,
...extra,
});
const flaky = findFlaky([
failure('one PR only'),
failure('one PR only'),
failure('re-run', { passedOnRerun: true }),
failure('retry', { suite: E2E, retried: true }),
failure('queue once', { event: 'merge_group', pr: 7 }),
failure('spread', { pr: 1 }),
failure('spread', { event: 'merge_group', pr: 2 }),
failure('spread', { pr: 3 }),
failure('spread', { suite: E2E, pr: 4 }),
]);
assert.deepEqual(
flaky.map((entry) => `${entry.suite.name} ${entry.test}`),
['Jest spread', 'Jest re-run', 'E2E retry'],
);
});
test('prOf reads the PR number from a merge queue branch', () => {
assert.equal(
prOf({
event: 'merge_group',
head_branch: 'gh-readonly-queue/main/pr-13616-0a1ca00c27f1',
}),
13616,
);
assert.equal(
prOf({ event: 'pull_request', pull_requests: [{ number: 42 }] }),
42,
);
});
test('rateLimitWait waits for retry-after or the hourly reset, and nothing else', () => {
const response = (status, headers) => ({
status,
headers: new Headers(headers),
});
const now = 1_000_000;
assert.equal(
rateLimitWait(response(429, { 'retry-after': '30' }), now),
30_000,
);
assert.equal(
rateLimitWait(
response(403, { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': '1060' }),
now,
),
61_000,
);
assert.equal(
rateLimitWait(response(403, { 'x-ratelimit-remaining': '12' }), now),
null,
);
assert.equal(rateLimitWait(response(500, {}), now), null);
});
test('slackMessages posts each suite on its own, escaped, top 10 with a link to the run', () => {
const STORYBOOK = { name: 'Storybook', root: 'frontend/' };
const entry = (suite, index) => ({
suite,
file: `src/t${index}.test.tsx`,
test: `T${index} › shows <Empty> & more`,
failures: 20 - index,
passedOnRerun: 1,
passedOnRetry: 0,
mergeQueue: 0,
prs: new Set([1]),
change: { who: 'dev' },
});
const messages = slackMessages(
'SigNoz/signoz',
'2026-11-17',
[JEST, STORYBOOK, E2E],
[
...Array.from({ length: 12 }, (_, index) => entry(JEST, index)),
entry(E2E, 0),
],
'https://github.com/SigNoz/signoz/actions/runs/1',
);
assert.deepEqual(
messages.map((message) => message.text),
['12 flaky Jest tests since 2026-11-17', '1 flaky E2E test since 2026-11-17'],
);
const sections = (message) =>
message.blocks.filter((block) => block.type === 'section');
assert.equal(sections(messages[0]).length, 10);
assert.equal(
sections(messages[0])[0].text.text,
'*20 failures* <https://github.com/SigNoz/signoz/blob/main/frontend/src/t0.test.tsx|T0 › shows &lt;Empty&gt; &amp; more>\npassed on re-run (1), last changed by dev',
);
assert.match(
sections(messages[1])[0].text.text,
/blob\/main\/tests\/e2e\/src\/t0\.test\.tsx/,
);
assert.equal(
messages[1].blocks.at(-1).elements[0].text,
'<https://github.com/SigNoz/signoz/actions/runs/1|All tests and their first error line>',
);
});

View File

@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { test } from 'node:test';
import SlowTestReporter from '../slow-test-reporter.mjs';
const result = {
testFilePath: path.join(process.cwd(), 'src/a/A.test.tsx'),
testResults: [
{ fullName: 'A › saves', duration: 2500 },
{ fullName: 'A › loads', duration: 100 },
{ fullName: 'A › reads a | b', duration: 4000 },
],
};
test('lists tests over 2 s in the job summary, slowest first', (t) => {
const summary = path.join(
mkdtempSync(path.join(tmpdir(), 'slow-')),
'summary.md',
);
writeFileSync(summary, '');
t.after(() => delete process.env.GITHUB_STEP_SUMMARY);
process.env.GITHUB_STEP_SUMMARY = summary;
const reporter = new SlowTestReporter();
reporter.onTestResult(undefined, result);
reporter.onRunComplete();
assert.equal(
readFileSync(summary, 'utf8'),
[
'### Jest tests over 2 s',
'',
'| Test | File | Time |',
'| --- | --- | --- |',
'| A › reads a \\| b | `src/a/A.test.tsx` | 4.0 s |',
'| A › saves | `src/a/A.test.tsx` | 2.5 s |',
'',
].join('\n'),
);
});

View File

@@ -0,0 +1,86 @@
const SLACK_LIMIT = 10;
function signal(entry) {
return [
entry.passedOnRetry && `passed on retry (${entry.passedOnRetry})`,
entry.passedOnRerun && `passed on re-run (${entry.passedOnRerun})`,
entry.mergeQueue && `merge queue (${entry.mergeQueue})`,
entry.prs.size > 1 && `${entry.prs.size} PRs`,
]
.filter(Boolean)
.join(', ');
}
const cell = (text) => text.replace(/\|/g, '\\|');
const changeCell = (change) =>
change
? `${change.who}, ${change.when}, [${change.sha}](${change.url})`
: 'unknown';
function suiteTable(suite, flaky) {
const rows = flaky
.filter((entry) => entry.suite === suite)
.map(
(entry) =>
`| ${cell(entry.test)} | \`${entry.file}\` | ${entry.failures} | ${signal(entry)} | ${cell(entry.error.slice(0, 80))} | ${changeCell(entry.change)} |`,
);
if (rows.length === 0) {
return [`### ${suite.name}`, '', 'No flaky tests found.', ''];
}
return [
`### ${suite.name}`,
'',
'| Test | File | Failures | Signal | First error line | Last change |',
'| --- | --- | --- | --- | --- | --- |',
...rows,
'',
];
}
export function report(since, suites, flaky) {
return [
`## Flaky tests since ${since}`,
'',
"A test is listed when it failed and then passed on a re-run of the same commit or on Playwright's own retry, or failed on 3 or more PRs. A merge queue run counts for the PR it was merging.",
'',
...suites.flatMap((suite) => suiteTable(suite, flaky)),
].join('\n');
}
// Slack mrkdwn treats these three as control characters.
const slackEscape = (text) =>
text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
function slackMessage(repo, since, suite, flaky, runUrl) {
const title = `${flaky.length} flaky ${suite.name} ${flaky.length === 1 ? 'test' : 'tests'} since ${since}`;
return {
text: title,
blocks: [
{ type: 'header', text: { type: 'plain_text', text: title } },
...flaky.slice(0, SLACK_LIMIT).map((entry) => ({
type: 'section',
text: {
type: 'mrkdwn',
text: `*${entry.failures} failures* <https://github.com/${repo}/blob/main/${suite.root}${entry.file}|${slackEscape(entry.test)}>\n${signal(entry)}, last changed by ${slackEscape(entry.change?.who ?? 'unknown')}`,
},
})),
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `<${runUrl}|All tests and their first error line>`,
},
],
},
],
};
}
export function slackMessages(repo, since, suites, flaky, runUrl) {
return suites
.map((suite) => [suite, flaky.filter((entry) => entry.suite === suite)])
.filter(([, entries]) => entries.length > 0)
.map(([suite, entries]) => slackMessage(repo, since, suite, entries, runUrl));
}

View File

@@ -0,0 +1,232 @@
#!/usr/bin/env node
import { pathToFileURL } from 'node:url';
import {
artifactFile,
artifactsSince,
gh,
mapLimit,
paginate,
} from './github-api.mjs';
import {
parseJest,
parsePlaywright,
parsePlaywrightReport,
} from './test-log-parsers.mjs';
import { report, slackMessages } from './flaky-test-format.mjs';
const MIN_PRS = 3;
const PARALLEL_RUNS = 8;
const DAY_MS = 24 * 60 * 60 * 1000;
const SUITES = [
{
name: 'Jest',
workflow: 'jsci.yaml',
job: /^test-shard \(\d+\)$|^test \/ js$/,
root: 'frontend/',
parse: parseJest,
},
{
name: 'Storybook',
workflow: 'jsci.yaml',
job: /^storybook \(\d+\)$/,
root: 'frontend/',
parse: parseJest,
},
{
name: 'E2E',
workflow: 'e2eci.yaml',
job: /^test \(/,
root: 'tests/e2e/',
parse: parsePlaywright,
// Uploaded by e2eci's upload-flaky step, only for shards with a test that passed on retry.
artifact: { prefix: 'e2e-flaky-', file: 'results.json' },
parseArtifact: parsePlaywrightReport,
},
];
export function findFlaky(failures) {
const byTest = new Map();
failures.forEach((failure) => {
const key = `${failure.suite.name}\0${failure.file}\0${failure.test}`;
const entry = byTest.get(key) ?? {
suite: failure.suite,
file: failure.file,
test: failure.test,
error: failure.error,
failures: 0,
prs: new Set(),
passedOnRerun: 0,
passedOnRetry: 0,
mergeQueue: 0,
};
entry.failures += 1;
if (failure.pr) {
entry.prs.add(failure.pr);
}
entry.passedOnRerun += failure.passedOnRerun ? 1 : 0;
entry.passedOnRetry += failure.retried ? 1 : 0;
entry.mergeQueue += failure.event === 'merge_group' ? 1 : 0;
byTest.set(key, entry);
});
return [...byTest.values()]
.filter(
(entry) =>
entry.passedOnRerun > 0 ||
entry.passedOnRetry > 0 ||
entry.prs.size >= MIN_PRS,
)
.sort((a, b) => b.failures - a.failures);
}
// Merge queue branches are named gh-readonly-queue/<base>/pr-<number>-<sha>.
export function prOf(run) {
if (run.event === 'merge_group') {
return Number(run.head_branch.match(/\/pr-(\d+)-/)?.[1]) || run.head_branch;
}
return run.pull_requests[0]?.number ?? run.head_branch;
}
async function runFailures(repo, run, suites) {
const jobs = await paginate(
`/repos/${repo}/actions/runs/${run.id}/jobs?filter=all&per_page=100`,
'jobs',
);
const failures = [];
for (const suite of suites) {
const suiteJobs = jobs.filter((job) => suite.job.test(job.name));
for (const job of suiteJobs.filter(
(failed) => failed.conclusion === 'failure',
)) {
const passedOnRerun = suiteJobs.some(
(later) =>
later.name === job.name &&
later.run_attempt > job.run_attempt &&
later.conclusion === 'success',
);
let log;
try {
log = await (await gh(`/repos/${repo}/actions/jobs/${job.id}/logs`)).text();
} catch (error) {
process.stderr.write(`skipped job ${job.id}: ${error.message}\n`);
continue;
}
suite.parse(log).forEach((failure) =>
failures.push({
...failure,
suite,
event: run.event,
pr: prOf(run),
passedOnRerun,
}),
);
}
}
return failures;
}
async function collectFailures(repo, since) {
const workflows = [...new Set(SUITES.map((suite) => suite.workflow))];
const failures = await Promise.all(
workflows.map(async (workflow) => {
const suites = SUITES.filter((suite) => suite.workflow === workflow);
const runs = await paginate(
`/repos/${repo}/actions/workflows/${workflow}/runs?created=>=${since}&per_page=100`,
'workflow_runs',
);
const candidates = runs.filter(
(run) => run.run_attempt > 1 || run.conclusion === 'failure',
);
const fromLogs = await mapLimit(candidates, PARALLEL_RUNS, (run) =>
runFailures(repo, run, suites),
);
const fromArtifacts = await Promise.all(
suites
.filter((suite) => suite.artifact)
.map((suite) => artifactFailures(repo, since, suite, runs)),
);
return [...fromLogs, ...fromArtifacts].flat(2);
}),
);
return failures.flat();
}
async function artifactFailures(repo, since, suite, runs) {
const runsById = new Map(runs.map((run) => [run.id, run]));
const artifacts = (await artifactsSince(repo, since)).filter(
(artifact) =>
artifact.name.startsWith(suite.artifact.prefix) &&
!artifact.expired &&
runsById.has(artifact.workflow_run.id),
);
return mapLimit(artifacts, PARALLEL_RUNS, async (artifact) => {
const run = runsById.get(artifact.workflow_run.id);
let report;
try {
report = JSON.parse(
await artifactFile(repo, artifact.id, suite.artifact.file),
);
} catch (error) {
process.stderr.write(`skipped artifact ${artifact.id}: ${error.message}\n`);
return [];
}
return suite.parseArtifact(report).map((failure) => ({
...failure,
suite,
event: run.event,
pr: prOf(run),
passedOnRerun: false,
}));
});
}
async function lastChange(repo, path) {
const [commit] = await (
await gh(`/repos/${repo}/commits?path=${path}&per_page=1`)
).json();
if (!commit) {
return null;
}
return {
who: commit.author?.login ?? commit.commit.author.name,
when: commit.commit.author.date.slice(0, 10),
sha: commit.sha.slice(0, 7),
url: commit.html_url,
};
}
async function postToSlack(webhook, message) {
const response = await fetch(webhook, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(message),
});
if (!response.ok) {
throw new Error(`${response.status} POST Slack webhook`);
}
}
async function main() {
const repo = process.env.GITHUB_REPOSITORY;
const days = Number(process.env.DAYS ?? 7);
const since = new Date(Date.now() - days * DAY_MS).toISOString().slice(0, 10);
const flaky = await Promise.all(
findFlaky(await collectFailures(repo, since)).map(async (entry) => ({
...entry,
change: await lastChange(repo, entry.suite.root + entry.file),
})),
);
process.stdout.write(report(since, SUITES, flaky));
const webhook = process.env.SLACK_WEBHOOK_URL;
if (webhook) {
const runUrl = `${process.env.GITHUB_SERVER_URL}/${repo}/actions/runs/${process.env.GITHUB_RUN_ID}`;
for (const message of slackMessages(repo, since, SUITES, flaky, runUrl)) {
await postToSlack(webhook, message);
}
}
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
await main();
}

View File

@@ -0,0 +1,119 @@
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const API = 'https://api.github.com';
const MAX_ATTEMPTS = 4;
const RETRY_BACKOFF_MS = 2000;
const MAX_ARTIFACT_BYTES = 64 * 1024 * 1024;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// GitHub sends `retry-after` (seconds) for a secondary limit, and `x-ratelimit-reset`
// (epoch seconds) once the hourly budget is spent.
export function rateLimitWait(response, now = Date.now()) {
if (response.status !== 403 && response.status !== 429) {
return null;
}
const retryAfter = Number(response.headers.get('retry-after'));
if (retryAfter) {
return retryAfter * 1000;
}
if (response.headers.get('x-ratelimit-remaining') !== '0') {
return null;
}
const reset = Number(response.headers.get('x-ratelimit-reset')) * 1000;
return Math.max(reset - now, 0) + 1000;
}
export async function gh(path, init = {}, attempt = 1) {
const retry = !init.method && attempt < MAX_ATTEMPTS;
let response;
try {
response = await fetch(path.startsWith('http') ? path : API + path, {
...init,
headers: {
accept: 'application/vnd.github+json',
authorization: `Bearer ${process.env.GH_TOKEN}`,
...init.headers,
},
});
} catch (error) {
if (!retry) {
throw error;
}
await sleep(attempt * RETRY_BACKOFF_MS);
return gh(path, init, attempt + 1);
}
const wait = rateLimitWait(response);
if (wait !== null) {
process.stderr.write(`rate limited, waiting ${Math.ceil(wait / 1000)} s\n`);
await sleep(wait);
return gh(path, init, attempt);
}
if (retry && response.status >= 500) {
await sleep(attempt * RETRY_BACKOFF_MS);
return gh(path, init, attempt + 1);
}
if (!response.ok) {
throw new Error(`${response.status} ${init.method ?? 'GET'} ${path}`);
}
return response;
}
export async function mapLimit(items, limit, fn) {
const results = [];
let next = 0;
await Promise.all(
Array.from({ length: limit }, async () => {
while (next < items.length) {
const index = next;
next += 1;
results[index] = await fn(items[index]);
}
}),
);
return results;
}
export async function paginate(path, key) {
const items = [];
let next = API + path;
while (next) {
const response = await gh(next);
const body = await response.json();
items.push(...(key ? body[key] : body));
next = response.headers.get('link')?.match(/<([^>]+)>; rel="next"/)?.[1];
}
return items;
}
// The artifacts list is newest first, so paging stops at the first page that reaches past `since`.
export async function artifactsSince(repo, since) {
const artifacts = [];
for (let page = 1; ; page += 1) {
const { artifacts: batch } = await (
await gh(`/repos/${repo}/actions/artifacts?per_page=100&page=${page}`)
).json();
artifacts.push(...batch.filter((artifact) => artifact.created_at >= since));
if (batch.length < 100 || batch.at(-1).created_at < since) {
return artifacts;
}
}
}
export async function artifactFile(repo, id, name) {
const dir = mkdtempSync(join(tmpdir(), 'artifact-'));
try {
const zip = join(dir, 'artifact.zip');
const response = await gh(`/repos/${repo}/actions/artifacts/${id}/zip`);
writeFileSync(zip, Buffer.from(await response.arrayBuffer()));
return execFileSync('unzip', ['-p', zip, name], {
encoding: 'utf8',
maxBuffer: MAX_ARTIFACT_BYTES,
});
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

View File

@@ -0,0 +1,45 @@
import fs from 'node:fs';
import path from 'node:path';
const budgetMs = Number(process.env.SLOW_TEST_MS ?? 2000);
class SlowTestReporter {
constructor() {
this.slow = [];
}
onTestResult(_test, result) {
const file = path.relative(process.cwd(), result.testFilePath);
result.testResults.forEach((test) => {
if ((test.duration ?? 0) > budgetMs) {
this.slow.push({ file, name: test.fullName, ms: test.duration });
}
});
}
onRunComplete() {
const summaryFile = process.env.GITHUB_STEP_SUMMARY;
if (!summaryFile || this.slow.length === 0) {
return;
}
const rows = this.slow
.sort((a, b) => b.ms - a.ms)
.map(
(test) =>
`| ${test.name.replace(/\|/g, '\\|')} | \`${test.file}\` | ${(test.ms / 1000).toFixed(1)} s |`,
);
fs.appendFileSync(
summaryFile,
[
`### Jest tests over ${budgetMs / 1000} s`,
'',
'| Test | File | Time |',
'| --- | --- | --- |',
...rows,
'',
].join('\n'),
);
}
}
export default SlowTestReporter;

View File

@@ -0,0 +1,110 @@
function cleanLines(log) {
return log.split('\n').map((line) =>
line
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[[0-9;]*m/g, '')
.replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z /, ''),
);
}
const firstLineAfter = (lines, index) =>
lines
.slice(index + 1, index + 8)
.map((next) => next.trim())
.find(Boolean) ?? '';
// Storybook's test runner prints `FAIL browser: chromium <file>`, then repeats
// the file with a `frontend/` prefix in its closing summary.
export function parseJest(log) {
const lines = cleanLines(log);
const failures = new Map();
let file = null;
lines.forEach((line, index) => {
const failedFile = line.match(
/^\s*FAIL\s+(?:browser: \S+\s+)?(?:frontend\/)?(\S+)/,
);
if (failedFile) {
[, file] = failedFile;
return;
}
const failedTest = line.match(/^\s*● (.+ › .+)$/);
if (!failedTest || !file) {
return;
}
const test = failedTest[1].trim();
const key = `${file}\0${test}`;
if (!failures.has(key)) {
failures.set(key, {
file,
test,
error: firstLineAfter(lines, index),
retried: false,
});
}
});
return [...failures.values()];
}
// Playwright's list reporter numbers each failure (`1) [chromium] › <file>:<line>:<col> › <title>`)
// and lists the tests that failed every retry under a closing `N failed` line.
export function parsePlaywright(log) {
const lines = cleanLines(log);
const testLine = /\[[^\]]+\] › (\S+?):\d+:\d+ › (.+?)\s*$/;
const errors = new Map();
const failures = [];
let section = null;
lines.forEach((line, index) => {
const header = line.match(/^\s*\d+\) /) && line.match(testLine);
if (header) {
errors.set(`${header[1]}\0${header[2]}`, firstLineAfter(lines, index));
return;
}
const count = line.match(
/^\s*\d+ (failed|flaky|passed|skipped|interrupted|did not run)\b/,
);
if (count) {
[, section] = count;
return;
}
const listed = section === 'failed' ? line.match(testLine) : null;
if (listed) {
const [, file, title] = listed;
failures.push({
file,
test: title,
error: errors.get(`${file}\0${title}`) ?? '',
retried: false,
});
}
});
return failures;
}
// Reads Playwright's JSON report. A flaky test failed and then passed on one of
// Playwright's own retries; spec files are relative to `config.rootDir`.
export function parsePlaywrightReport(report) {
const dir = report.config.rootDir.split('/tests/e2e/')[1];
const flaky = [];
const walk = (suite, titles) => {
suite.specs?.forEach((spec) => {
if (!spec.tests.some((test) => test.status === 'flaky')) {
return;
}
const error = spec.tests
.flatMap((test) => test.results)
.find((result) => result.error)?.error.message;
flaky.push({
file: [dir, spec.file].filter(Boolean).join('/'),
test: [...titles, spec.title].join(' › '),
error:
cleanLines(error ?? '')
.find((line) => line.trim())
?.trim() ?? '',
retried: true,
});
});
suite.suites?.forEach((child) => walk(child, [...titles, child.title]));
};
report.suites.forEach((fileSuite) => walk(fileSuite, []));
return flaky;
}

View File

@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
pathname === ROUTES.SETTINGS ||
pathname === ROUTES.BILLING ||
pathname === ROUTES.MEMBERS_SETTINGS ||
pathname === ROUTES.ORG_SETTINGS ||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
(isAdmin &&
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&

View File

@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.BILLING);
});
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
@@ -1707,7 +1707,6 @@ describe('PrivateRoute', () => {
// Everything under /settings resolves to the non-exact SETTINGS route
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
ORG_SETTINGS: { path: ROUTES.ORG_SETTINGS, deniedRoles: DENIED_ROLES },
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
ROLE_DETAILS: {

View File

@@ -17,11 +17,13 @@ function loadGetModule(href: string): GetModule {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../get');
});
base.remove();
return mod;
}
afterEach(() => {
for (const el of document.head.querySelectorAll('base')) {
el.remove();
}
localStorage.clear();
});

View File

@@ -15,11 +15,13 @@ function loadGetModule(href: string): GetModule {
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
mod = require('../get');
});
base.remove();
return mod;
}
afterEach(() => {
for (const el of document.head.querySelectorAll('base')) {
el.remove();
}
sessionStorage.clear();
});

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,4 @@
import { render } from '@testing-library/react';
import { screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import getLocal from '../../../api/browser/localstorage/get';
import AppLoading from '../AppLoading';
@@ -16,6 +15,7 @@ describe('AppLoading', () => {
const SIGNOZ_TEXT = 'SigNoz';
const TAGLINE_TEXT =
'OpenTelemetry-Native Logs, Metrics and Traces in a single pane';
const CONTAINER_SELECTOR = '.app-loading-container';
beforeEach(() => {
jest.clearAllMocks();
@@ -33,7 +33,7 @@ describe('AppLoading', () => {
expect(screen.getByText(TAGLINE_TEXT)).toBeInTheDocument();
// Check if dark theme class is applied
const container = screen.getByTestId('app-loading-container');
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
expect(container).toHaveClass('dark');
expect(container).not.toHaveClass('lightMode');
});
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
expect(tagline).toBeInTheDocument();
// Check for loader
const loader = screen.getByTestId('app-loading-loader');
const loader = document.querySelector('.loader');
expect(loader).toBeInTheDocument();
});
@@ -72,7 +72,7 @@ describe('AppLoading', () => {
// Should still render with dark theme as fallback
expect(screen.getByText(SIGNOZ_TEXT)).toBeInTheDocument();
const container = screen.getByTestId('app-loading-container');
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
expect(container).toHaveClass('dark');
});
});

View File

@@ -3,7 +3,7 @@ import { Toaster } from '@signozhq/ui/toast';
const PAGE_INSET = { bottom: 'var(--bottom-strip-height, 0px)' };
function AppToaster(): JSX.Element {
return <Toaster position="top-right" pageInset={PAGE_INSET} />;
return <Toaster position="bottom-right" pageInset={PAGE_INSET} />;
}
export default AppToaster;

View File

@@ -1,25 +0,0 @@
.scrollHint {
position: sticky;
bottom: 0;
height: 0;
}
.scrollButton {
position: absolute;
bottom: var(--spacing-7);
left: 50%;
transform: translateX(-50%);
}
.scrollIcon {
animation: pulse 1s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -0,0 +1,129 @@
.changelog-modal {
.ant-modal-content {
padding: unset;
background-color: var(--l2-background);
.ant-modal-header {
margin-bottom: unset;
}
.ant-modal-footer {
margin-top: unset;
}
}
&-title {
display: flex;
align-items: center;
gap: 8px;
background-color: var(--l2-background);
padding: 16px;
font-size: 14px;
line-height: 20px;
color: var(--l1-foreground);
border-bottom: 1px solid var(--l1-border);
}
&-footer.scroll-available {
.scroll-btn-container {
display: block;
}
}
&-footer {
position: relative;
border: 1px solid var(--l1-border);
padding: 12px;
display: flex;
align-items: center;
justify-content: space-between;
&-label {
color: var(--text-robin-400);
font-size: 14px;
line-height: 24px;
position: relative;
padding-left: 14px;
&::before {
content: '';
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 6px;
height: 6px;
border-radius: 100%;
background-color: var(--primary-background);
}
}
&-ctas {
display: flex;
margin-left: auto;
& svg {
font-size: 14px;
}
}
.scroll-btn-container {
display: none;
position: absolute;
top: -40px;
left: 50%;
transform: translateX(-50%);
.scroll-btn {
all: unset;
padding: 4px 12px 4px 10px;
background-color: var(--l1-border);
border-radius: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
transition: background-color 0.1s;
&:hover {
background-color: var(--l1-border);
}
&:active {
background-color: var(--l1-border);
}
span {
font-size: 12px;
line-height: 18px;
color: var(--l2-foreground);
}
// add animation to the chevrons down icon
svg {
animation: pulse 1s infinite;
}
}
}
}
&-content {
max-height: calc(100vh - 300px);
overflow-y: auto;
padding: 16px 16px 18px 16px;
border: 1px solid var(--l1-border);
border-top-width: 0;
border-bottom-width: 0;
}
}
// pulse for the scroll for more icon
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -1,9 +1,10 @@
import { useEffect } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
import dayjs from 'dayjs';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
@@ -12,9 +13,8 @@ import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogRenderer from './components/ChangelogRenderer';
import { useChangelogScroll } from './useChangelogScroll';
import styles from './ChangelogModal.module.scss';
import './ChangelogModal.styles.scss';
interface Props {
changelog: ChangelogSchema;
@@ -22,7 +22,8 @@ interface Props {
}
function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
const { contentRef, hasScroll, scrollForMore } = useChangelogScroll();
const [hasScroll, setHasScroll] = useState(false);
const changelogContentSectionRef = useRef<HTMLDivElement>(null);
const { userPreferences, updateUserPreferenceInContext } = useAppContext();
const formattedReleaseDate = dayjs(changelog?.release_date).format(
@@ -56,6 +57,30 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
updateUserPreferenceInContext,
]);
const checkScroll = useCallback((): void => {
if (changelogContentSectionRef.current) {
const { scrollHeight, clientHeight, scrollTop } =
changelogContentSectionRef.current;
const isAtBottom = scrollHeight - clientHeight - scrollTop <= 8;
setHasScroll(scrollHeight > clientHeight + 24 && !isAtBottom); // 24px - buffer height to show show more
}
}, []);
useEffect(() => {
checkScroll();
const changelogContentSection = changelogContentSectionRef.current;
if (changelogContentSection) {
changelogContentSection.addEventListener('scroll', checkScroll);
}
return (): void => {
if (changelogContentSection) {
changelogContentSection.removeEventListener('scroll', checkScroll);
}
};
}, [checkScroll]);
const onClickUpdateWorkspace = (): void => {
window.open(
'https://signoz.io/upgrade-path',
@@ -64,61 +89,75 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
);
};
const onClickScrollForMore = (): void => {
if (changelogContentSectionRef.current) {
changelogContentSectionRef.current.scrollTo({
top: changelogContentSectionRef.current.scrollTop + 600, // Scroll 600px from the current position
behavior: 'smooth',
});
}
};
// TODO: antd stacks at 1000, under `@signozhq/ui` dialogs (1001). It opens on
// its own a second after load, so a dialog opened from a deep link
// (`?add-key`, `?invite=true`) covers it. Moving to the `@signozhq/ui` Dialog
// fixes it.
return (
<Dialog
<Modal
className={cx('changelog-modal')}
title={
<div className="changelog-modal-title">
<ScrollText size={16} />
What’s New ⎯ Changelog : {formattedReleaseDate}
</div>
}
width={820}
open
onClose={onClose}
title={`What’s New ⎯ Changelog : ${formattedReleaseDate}`}
titleIcon={<ScrollText size={16} />}
width="extra-wide"
testId="changelog-dialog"
footerSuffix={
isCloudUser ? undefined : (
<>
<Button
variant="outlined"
color="secondary"
size="md"
prefix={<X size={12} />}
onClick={onClose}
testId="changelog-skip-btn"
>
Skip for now
</Button>
<Button
variant="solid"
color="primary"
size="md"
prefix={<Check size={12} />}
onClick={onClickUpdateWorkspace}
testId="changelog-update-btn"
>
Update my workspace
</Button>
</>
)
onCancel={onClose}
footer={
<div
className={cx('changelog-modal-footer', hasScroll && 'scroll-available')}
>
{!isCloudUser && (
<div className="changelog-modal-footer-ctas">
<Button type="default" onClick={onClose}>
<Flex align="center" gap="4px">
<X size="md" />
Skip for now
</Flex>
</Button>
<Button type="primary" onClick={onClickUpdateWorkspace}>
<Flex align="center" gap="4px">
<Check size="md" />
Update my workspace
</Flex>
</Button>
</div>
)}
{changelog && (
<div className="scroll-btn-container">
<button
data-testid="scroll-more-btn"
type="button"
className="scroll-btn"
onClick={onClickScrollForMore}
>
<ChevronsDown size={14} />
<span>Scroll for more</span>
</button>
</div>
)}
</div>
}
>
<div data-testid="changelog-content" ref={contentRef}>
<ChangelogRenderer changelog={changelog} />
<div
className="changelog-modal-content"
data-testid="changelog-content"
ref={changelogContentSectionRef}
>
{changelog && <ChangelogRenderer changelog={changelog} />}
</div>
{hasScroll && (
<div className={styles.scrollHint}>
<div className={styles.scrollButton}>
<Button
variant="solid"
color="primary"
size="sm"
prefix={<ChevronsDown size={14} className={styles.scrollIcon} />}
onClick={scrollForMore}
testId="scroll-more-btn"
>
Scroll for more
</Button>
</div>
</div>
)}
</Dialog>
</Modal>
);
}

View File

@@ -1,23 +1,12 @@
import { ReactNode } from 'react';
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { fireEvent, render, screen } from '@testing-library/react';
import { USER_PREFERENCES } from 'constants/userPreferences';
import { IAppContext } from 'providers/App/types';
import {
fireEvent,
getAppContextMock,
render,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
import {
LicensePlatform,
LicenseResModel,
} from 'types/api/licensesV3/getActive';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogModal from '../ChangelogModal';
@@ -51,165 +40,71 @@ const mockChangelog: ChangelogSchema = {
jest.mock(
'react-markdown',
() =>
function ReactMarkdown({ children }: { children: ReactNode }): JSX.Element {
function ReactMarkdown({ children }: any) {
return <div>{children}</div>;
},
);
const seenChangelogVersion: UserPreference = {
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
description: '',
valueType: 'string',
defaultValue: '',
allowedValues: [],
allowedScopes: ['user'],
value: 'v1.0.0',
};
const selfHostedContext: Partial<IAppContext> = {
activeLicense: {
...(getAppContextMock('ADMIN').activeLicense as LicenseResModel),
platform: LicensePlatform.SELF_HOSTED,
},
};
function renderChangelog(
onClose: () => void = jest.fn(),
appContextOverrides: Partial<IAppContext> = {},
): void {
render(
<ChangelogModal changelog={mockChangelog} onClose={onClose} />,
undefined,
{
appContextOverrides: {
userPreferences: [seenChangelogVersion],
...appContextOverrides,
// mock useAppContext
jest.mock('providers/App/App', () => ({
useAppContext: jest.fn(() => ({
updateUserPreferenceInContext: jest.fn(),
userPreferences: [
{
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
value: 'v1.0.0',
},
},
],
})),
}));
function renderChangelog(onClose: () => void = jest.fn()): void {
render(
<MockQueryClientProvider>
<ChangelogModal changelog={mockChangelog} onClose={onClose} />
</MockQueryClientProvider>,
);
}
describe('ChangelogModal', () => {
it('renders the dialog with the changelog data', async () => {
it('renders modal with changelog data', () => {
renderChangelog();
await expect(
screen.findByTestId('changelog-dialog-title'),
).resolves.toHaveTextContent('What’s New ⎯ Changelog : June 10, 2025');
expect(
screen.getByText('What’s New ⎯ Changelog : June 10, 2025'),
).toBeInTheDocument();
expect(screen.getByText('Feature 1')).toBeInTheDocument();
expect(screen.getByText('Description for feature 1')).toBeInTheDocument();
expect(screen.getByText('Bug fix details')).toBeInTheDocument();
expect(screen.getByText('Maintenance details')).toBeInTheDocument();
});
it('calls onClose when the close button is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
it('calls onClose when Skip for now is clicked', () => {
const onClose = jest.fn();
renderChangelog(onClose);
await user.click(await screen.findByTestId('changelog-dialog-close'));
expect(onClose).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByText('Skip for now'));
expect(onClose).toHaveBeenCalled();
});
it('offers no upgrade actions to a cloud workspace', async () => {
it('opens migration docs when Update my workspace is clicked', () => {
window.open = jest.fn();
renderChangelog();
await screen.findByTestId('changelog-content');
expect(
screen.queryByTestId('changelog-dialog-footer'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-skip-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-update-btn')).not.toBeInTheDocument();
});
it('calls onClose when Skip for now is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderChangelog(onClose, selfHostedContext);
await user.click(await screen.findByTestId('changelog-skip-btn'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('opens migration docs when Update my workspace is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
renderChangelog(jest.fn(), selfHostedContext);
await user.click(await screen.findByTestId('changelog-update-btn'));
expect(open).toHaveBeenCalledWith(
fireEvent.click(screen.getByText('Update my workspace'));
expect(window.open).toHaveBeenCalledWith(
'https://signoz.io/upgrade-path',
'_blank',
'noopener,noreferrer',
);
open.mockRestore();
});
describe('scroll for more', () => {
let scrollHeight: jest.SpyInstance;
let clientHeight: jest.SpyInstance;
beforeEach(() => {
scrollHeight = jest.spyOn(Element.prototype, 'scrollHeight', 'get');
clientHeight = jest.spyOn(Element.prototype, 'clientHeight', 'get');
});
afterEach(() => {
scrollHeight.mockRestore();
clientHeight.mockRestore();
});
it('is hidden while the content fits', async () => {
scrollHeight.mockReturnValue(400);
clientHeight.mockReturnValue(400);
renderChangelog();
await screen.findByTestId('changelog-content');
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument();
});
it('scrolls 600px further from the current position when clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
scrollHeight.mockReturnValue(2000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
Object.defineProperty(content, 'scrollTop', {
value: 100,
configurable: true,
});
const scrollTo = jest.fn();
Object.defineProperty(content, 'scrollTo', { value: scrollTo });
await user.click(await screen.findByTestId('scroll-more-btn'));
expect(scrollTo).toHaveBeenCalledWith({
top: 700,
behavior: 'smooth',
});
});
it('hides once the content is scrolled to the bottom', async () => {
scrollHeight.mockReturnValue(1000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
await screen.findByTestId('scroll-more-btn');
Object.defineProperty(content, 'scrollTop', {
value: 600,
configurable: true,
});
fireEvent.scroll(content);
await waitFor(() =>
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument(),
);
});
it('scrolls for more when Scroll for more is clicked', () => {
renderChangelog();
const scrollBtn = screen.getByTestId('scroll-more-btn');
const contentDiv = screen.getByTestId('changelog-content');
if (contentDiv) {
contentDiv.scrollTo = jest.fn();
}
fireEvent.click(scrollBtn);
if (contentDiv) {
expect(contentDiv.scrollTo).toHaveBeenCalled();
}
});
});

View File

@@ -34,7 +34,7 @@
&-line {
position: absolute;
left: 3px;
left: 0;
top: 6px;
bottom: -30px;
width: 1px;

View File

@@ -1,52 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
const SCROLL_STEP_PX = 600;
const MIN_OVERFLOW_PX = 24;
const BOTTOM_TOLERANCE_PX = 8;
interface UseChangelogScrollReturn {
contentRef: (node: HTMLDivElement | null) => void;
hasScroll: boolean;
scrollForMore: () => void;
}
export function useChangelogScroll(): UseChangelogScrollReturn {
const [content, setContent] = useState<HTMLElement | null>(null);
const [hasScroll, setHasScroll] = useState(false);
const checkScroll = useCallback((): void => {
if (!content) {
return;
}
const { scrollHeight, clientHeight, scrollTop } = content;
const isAtBottom =
scrollHeight - clientHeight - scrollTop <= BOTTOM_TOLERANCE_PX;
setHasScroll(scrollHeight > clientHeight + MIN_OVERFLOW_PX && !isAtBottom);
}, [content]);
useEffect(() => {
if (!content) {
return undefined;
}
checkScroll();
content.addEventListener('scroll', checkScroll);
return (): void => {
content.removeEventListener('scroll', checkScroll);
};
}, [content, checkScroll]);
const scrollForMore = useCallback((): void => {
content?.scrollTo({
top: content.scrollTop + SCROLL_STEP_PX,
behavior: 'smooth',
});
}, [content]);
// The dialog body owns the scroll; a second scroller inside it shows two scrollbars.
const contentRef = useCallback((node: HTMLDivElement | null): void => {
setContent(node?.closest<HTMLElement>('[data-slot="dialog-body"]') ?? null);
}, []);
return { contentRef, hasScroll, scrollForMore };
}

View File

@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
});
it('submit button becomes disabled after clearing the name field', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
@@ -86,7 +86,7 @@ describe('CreateServiceAccountModal', () => {
});
it('successful submit shows toast.success and closes modal', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');
@@ -112,7 +112,7 @@ describe('CreateServiceAccountModal', () => {
});
it('pressing Enter again while creating sends one request', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
let requests = 0;
server.use(
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) => {
@@ -146,7 +146,7 @@ describe('CreateServiceAccountModal', () => {
});
it('shows toast.error on API error and keeps modal open', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
@@ -186,7 +186,7 @@ describe('CreateServiceAccountModal', () => {
});
it('Cancel button closes modal without submitting', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const cancelBtn = await screen.findByTestId('create-sa-cancel-btn');
@@ -217,7 +217,7 @@ describe('CreateServiceAccountModal', () => {
});
it('keeps the footer usable when create permission is denied', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(setupAuthzDenyAll());
renderModal();
@@ -242,7 +242,7 @@ describe('CreateServiceAccountModal', () => {
});
it('shows "Name is required" after clearing the name field', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input-field');

View File

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

View File

@@ -640,14 +640,12 @@ function CustomTimePicker({
size={14}
className="cursor-pointer time-input-suffix-icon-badge"
onClick={handleClose}
data-testid="time-picker-close-chevron"
/>
) : (
<ChevronDown
size={14}
className="cursor-pointer time-input-suffix-icon-badge"
onClick={handleOpen}
data-testid="time-picker-open-chevron"
/>
)}
</div>

View File

@@ -273,7 +273,7 @@ describe('EditMemberDrawer', () => {
it('enables Save after editing name and calls updateUser on confirm', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockMutateAsync = jest.fn().mockResolvedValue({});
(useUpdateUser as jest.Mock).mockReturnValue({
@@ -306,7 +306,7 @@ describe('EditMemberDrawer', () => {
it('does not close the drawer after a successful save', async () => {
const onClose = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ onClose });
@@ -331,7 +331,7 @@ describe('EditMemberDrawer', () => {
it('adding a new role creates a user role without removing existing ones', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockSet = jest.fn().mockResolvedValue({});
(useCreateUserRole as jest.Mock).mockReturnValue({
@@ -365,7 +365,7 @@ describe('EditMemberDrawer', () => {
it('deselecting a role deletes the user role by its assignment id', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ onComplete });
@@ -392,7 +392,7 @@ describe('EditMemberDrawer', () => {
it('shows delete confirm dialog and calls deleteUser for active members', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -553,7 +553,7 @@ describe('EditMemberDrawer', () => {
it('calls deleteUser after confirming revoke invite for invited members', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -583,7 +583,7 @@ describe('EditMemberDrawer', () => {
it('calls updateUser when saving name change for an invited member', async () => {
const onComplete = jest.fn();
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockMutateAsync = jest.fn().mockResolvedValue({});
(useGetUser as jest.Mock).mockReturnValue({
@@ -641,7 +641,7 @@ describe('EditMemberDrawer', () => {
});
it('shows SaveErrorItem when updateUser fails for name change', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useUpdateUser as jest.Mock).mockReturnValue({
mutateAsync: jest.fn().mockRejectedValue(new Error('server error')),
@@ -669,7 +669,7 @@ describe('EditMemberDrawer', () => {
});
it('shows API error message when deleteUser fails for active member', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -700,7 +700,7 @@ describe('EditMemberDrawer', () => {
});
it('shows API error message when deleteUser fails for invited member', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
mutateAsync: mockDeleteMutate.mockImplementation(() => {
@@ -740,7 +740,7 @@ describe('EditMemberDrawer', () => {
});
it('does not open delete confirm dialog when Delete is clicked while disabled (isSelf)', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ member: selfMember });
await user.click(screen.getByRole('button', { name: /delete member/i }));
@@ -811,7 +811,7 @@ describe('EditMemberDrawer', () => {
isLoading: false,
});
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer({ member: selfMember });
const input = await screen.findByDisplayValue('Alice Smith');
@@ -875,7 +875,7 @@ describe('EditMemberDrawer', () => {
});
it('does not open delete confirm dialog when Delete is clicked while disabled (root)', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
await user.click(screen.getByRole('button', { name: /delete member/i }));
@@ -886,7 +886,7 @@ describe('EditMemberDrawer', () => {
});
it('does not call createResetPasswordToken when Reset Link is clicked while disabled (root)', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
await user.click(
@@ -903,7 +903,7 @@ describe('EditMemberDrawer', () => {
});
it('calls POST and opens the reset link dialog with the generated link and expiry', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
@@ -925,7 +925,7 @@ describe('EditMemberDrawer', () => {
});
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const mockToast = jest.mocked(toast);
renderDrawer();

View File

@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
// Click the close button
const closeButton = screen.getByTestId('close-button');
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(closeButton);
// Check if onClose was called
@@ -145,7 +145,7 @@ it('should open the modal when the trigger component is clicked', async () => {
// Click the trigger component
const triggerButton = screen.getByText('Open Error Modal');
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(triggerButton);
// Check if the modal is displayed
@@ -165,13 +165,12 @@ it('should close the modal when the onCancel event is triggered', async () => {
// Click the trigger component
const triggerButton = screen.getByText('error');
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(triggerButton);
await waitFor(() => {
expect(screen.getByText('An error occurred')).toBeInTheDocument();
});
const modal = screen.getByRole('dialog');
// Trigger the onCancel event
await user.click(screen.getByTestId('close-button'));
@@ -181,6 +180,8 @@ it('should close the modal when the onCancel event is triggered', async () => {
await waitFor(() => {
// check if the modal is not visible
expect(modal).toHaveStyle({ display: 'none' });
const modal = document.getElementsByClassName('ant-modal');
const style = window.getComputedStyle(modal[0]);
expect(style.display).toBe('none');
});
});

View File

@@ -1,6 +1,6 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { act, render, renderHook } from 'tests/test-utils';
import { act, render, renderHook } from '@testing-library/react';
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
import { useGlobalTimeStore } from 'store/globalTime/globalTimeStore';
@@ -42,13 +42,13 @@ describe('GlobalTimeStoreAdapter', () => {
globalTime: createGlobalTimeState(),
});
const { asFragment } = render(
const { container } = render(
<Provider store={store}>
<GlobalTimeStoreAdapter />
</Provider>,
);
expect(asFragment().hasChildNodes()).toBe(false);
expect(container.firstChild).toBeNull();
});
it('should sync relative time from Redux to Zustand store', () => {

View File

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

View File

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

View File

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

View File

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

View File

@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
});
it('adds a row when "Add another" is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={2} />);
@@ -27,7 +27,7 @@ describe('InviteMembers - Row Management', () => {
});
it('removes a row when trash button is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={3} />);
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
});
it('respects minRows constraint when removing rows', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={2} minRows={2} />);
@@ -62,7 +62,7 @@ describe('InviteMembers - Row Management', () => {
});
it('cannot remove rows below minRows=1 default', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={2} />);
@@ -76,7 +76,7 @@ describe('InviteMembers - Row Management', () => {
});
it('preserves data in other rows when removing one', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<InviteMembers initialRowCount={3} />);

View File

@@ -22,7 +22,7 @@ describe('InviteMembers - Validation', () => {
describe('email validation', () => {
it('shows email validation error when email is invalid and role is selected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
});
it('shows inline error for invalid email field', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears validation error when email is corrected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -104,7 +104,7 @@ describe('InviteMembers - Validation', () => {
describe('role validation', () => {
it('shows role validation error when role is missing', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
});
it('clears role validation error when role is selected', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -159,7 +159,7 @@ describe('InviteMembers - Validation', () => {
describe('combined validation', () => {
it('shows combined error when both email and role are invalid', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers
@@ -186,7 +186,7 @@ describe('InviteMembers - Validation', () => {
describe('touched rows', () => {
it('only validates touched rows (rows with email or role)', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<InviteMembers

View File

@@ -14,14 +14,14 @@ export type CreatedByProps =
creatorOptions: CreatorOption[];
createdBy: string[];
onCreatedByChange: (emails: string[]) => void;
// Run a Created-by change made with the dropdown closed.
onCreatedByCommit: (emails: string[]) => void;
// Clear all Created-by selections and run immediately.
onClearCreatedBy: () => void;
}
| {
creatorOptions?: undefined;
createdBy?: undefined;
onCreatedByChange?: undefined;
onCreatedByCommit?: undefined;
onClearCreatedBy?: undefined;
};
type Props = CreatedByProps & {
@@ -61,8 +61,8 @@ function FilterChips(props: Props): JSX.Element {
placeholder="Created by"
testId={`${testIdPrefix}-filter-created-by`}
disabled={disabled}
onClear={props.onClearCreatedBy}
onChange={props.onCreatedByChange}
onCommit={props.onCreatedByCommit}
onDropdownVisibleChange={runOnClose}
/>
)}

View File

@@ -81,7 +81,7 @@ function FilterZone({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleCreatedByCommit,
handleClearCreatedBy,
handleClear,
} = useFilterZoneDraft({
query,
@@ -96,7 +96,7 @@ function FilterZone({
creatorOptions,
createdBy: reflected.createdBy,
onCreatedByChange: handleCreatedByChange,
onCreatedByCommit: handleCreatedByCommit,
onClearCreatedBy: handleClearCreatedBy,
}
: {};

View File

@@ -1,4 +1,3 @@
import { useCallback, useState } from 'react';
import { ConfigProvider, Select } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
import cx from 'classnames';
@@ -21,9 +20,7 @@ interface Props {
placeholder: string;
testId: string;
onChange: (values: string[]) => void;
// A change made with the dropdown closed (a tag's ×, the clear icon) has no
// close to run on, so it is committed here instead of staged via onChange.
onCommit: (values: string[]) => void;
onClear?: () => void;
onDropdownVisibleChange?: (open: boolean) => void;
disabled?: boolean;
}
@@ -34,31 +31,10 @@ function MultiSelectFilter({
placeholder,
testId,
onChange,
onCommit,
onClear,
onDropdownVisibleChange,
disabled = false,
}: Props): JSX.Element {
const [isOpen, setIsOpen] = useState(false);
const handleChange = useCallback(
(next: string[]): void => {
if (!isOpen) {
onCommit(next);
return;
}
onChange(next);
},
[isOpen, onChange, onCommit],
);
const handleDropdownVisibleChange = useCallback(
(nextOpen: boolean): void => {
setIsOpen(nextOpen);
onDropdownVisibleChange?.(nextOpen);
},
[onDropdownVisibleChange],
);
return (
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
<Select
@@ -75,6 +51,7 @@ function MultiSelectFilter({
menuItemSelectedIcon={null}
data-testid={testId}
disabled={disabled}
onClear={onClear}
optionRender={(option): JSX.Element => (
<div
className={styles.checkOption}
@@ -89,8 +66,8 @@ function MultiSelectFilter({
<span className={styles.checkOptionLabel}>{option.label}</span>
</div>
)}
onChange={(next): void => handleChange(next as string[])}
onDropdownVisibleChange={handleDropdownVisibleChange}
onChange={(next): void => onChange(next as string[])}
onDropdownVisibleChange={onDropdownVisibleChange}
/>
</ConfigProvider>
);

View File

@@ -1,5 +1,4 @@
import userEvent from '@testing-library/user-event';
import { render, screen, within } from 'tests/test-utils';
import { render, screen } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import FilterZone from '../FilterZone';
@@ -48,33 +47,4 @@ describe('FilterZone', () => {
).not.toBeInTheDocument();
expect(screen.getByTestId('things-filter-updated')).toBeInTheDocument();
});
it('runs the query when a creator is removed with the dropdown closed', async () => {
const user = userEvent.setup();
const onQueryChange = jest.fn();
render(
<FilterZone
query="created_by = 'ada@example.com'"
grammar={grammar}
testIdPrefix="things"
creatorOptions={[{ email: 'ada@example.com', label: 'Ada' }]}
source={source}
onQueryChange={onQueryChange}
/>,
);
// antd renders the tag's × aria-hidden.
await user.click(
within(screen.getByTitle('Ada')).getByRole('img', {
name: 'close',
hidden: true,
}),
);
expect(
within(screen.getByTestId('things-filter-created-by')).getByRole('combobox'),
).toHaveAttribute('aria-expanded', 'false');
expect(onQueryChange).toHaveBeenCalledWith('');
});
});

View File

@@ -106,20 +106,12 @@ describe('useFilterZoneDraft', () => {
"created_by = 'a@x.io' AND name = 'x'",
);
act(() => result.current.handleCreatedByCommit([]));
act(() => result.current.handleClearCreatedBy());
expect(result.current.draft).toBe("name = 'x'");
expect(onQueryChange).toHaveBeenCalledWith("name = 'x'");
});
it('runs the remaining creators when one is removed', () => {
const { result, onQueryChange } = setup("created_by IN ['a@x.io', 'b@x.io']");
act(() => result.current.handleCreatedByCommit(['b@x.io']));
expect(onQueryChange).toHaveBeenCalledWith("created_by = 'b@x.io'");
});
it('empties the draft and runs the empty query on clear', () => {
const { result, onQueryChange, onCleared, onClearAll } = setup();

View File

@@ -31,7 +31,7 @@ interface FilterZoneDraft {
applyDraft: (next: string) => void;
handleCreatedByChange: (emails: string[]) => void;
handleUpdatedChange: (window: UpdatedWindow) => void;
handleCreatedByCommit: (emails: string[]) => void;
handleClearCreatedBy: () => void;
handleClear: () => void;
}
@@ -97,14 +97,10 @@ export function useFilterZoneDraft({
[draft, applyDraft, onFilterApplied],
);
// Runs a Created-by change made with its dropdown closed.
const handleCreatedByCommit = useCallback(
(emails: string[]): void => {
onFilterApplied?.('createdBy', { valueCount: emails.length });
applyDraft(spliceClause(draft, 'created_by', createdByClause(emails)));
},
[draft, applyDraft, onFilterApplied],
);
// Clear-all on the Created-by select removes its clause and runs immediately.
const handleClearCreatedBy = useCallback((): void => {
applyDraft(spliceClause(draft, 'created_by', null));
}, [draft, applyDraft]);
// Clear resets the draft and runs immediately (empty query).
const handleClear = useCallback((): void => {
@@ -126,7 +122,7 @@ export function useFilterZoneDraft({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleCreatedByCommit,
handleClearCreatedBy,
handleClear,
};
}

View File

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

View File

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

View File

@@ -24,7 +24,6 @@ interface Props {
confirmLabel: string;
/** Name the input holds each time the dialog opens. */
initialName?: string;
placeholder: string;
testIdPrefix: string;
}
@@ -36,7 +35,6 @@ function ViewNameDialog({
description,
confirmLabel,
initialName = '',
placeholder,
testIdPrefix,
}: Props): JSX.Element {
const [name, setName] = useState(initialName);
@@ -118,7 +116,7 @@ function ViewNameDialog({
id={inputId}
value={name}
maxLength={VIEW_NAME_MAX_LENGTH}
placeholder={placeholder}
placeholder="e.g. Prod alerts"
autoComplete="off"
testId={`${testIdPrefix}-name`}
onChange={(e: ChangeEvent<HTMLInputElement>): void =>

View File

@@ -39,7 +39,6 @@ interface Props {
saveTestIdPrefix?: string;
renameTestIdPrefix?: string;
customSectionLabel?: string;
viewNamePlaceholder?: string;
deleteDescription?: string;
/** Wraps the rail body, e.g. in an authz guard. */
guard?: (content: ReactElement) => ReactElement;
@@ -68,7 +67,6 @@ function ViewsRail({
saveTestIdPrefix = 'save-view',
renameTestIdPrefix = 'rename-view',
customSectionLabel = 'My views',
viewNamePlaceholder = 'e.g. Production',
deleteDescription = 'This removes the saved view.',
guard,
onViewSaved,
@@ -289,7 +287,6 @@ function ViewsRail({
title="Save as view"
description="Save the current filters as a view you can return to."
confirmLabel="Save view"
placeholder={viewNamePlaceholder}
testIdPrefix={saveTestIdPrefix}
/>
<ViewNameDialog
@@ -300,7 +297,6 @@ function ViewsRail({
description="The view keeps its filters under the new name."
confirmLabel="Rename"
initialName={renameTarget?.label}
placeholder={viewNamePlaceholder}
testIdPrefix={renameTestIdPrefix}
/>
{contextHolder}

View File

@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
});
it('selects a view by id', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const props = renderRail();
await user.click(screen.getByTestId(`${PREFIX}-view-view-2`));
@@ -61,7 +61,7 @@ describe('ViewsRail', () => {
});
it('filters views by name and says when none match', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderRail();
const search = screen.getByTestId(`${PREFIX}-view-search-field`);
@@ -109,7 +109,7 @@ describe('ViewsRail', () => {
});
it('offers save, save as and reset for a modified custom view', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onViewSaved = jest.fn();
const props = renderRail({
activeViewId: 'view-1',
@@ -138,7 +138,7 @@ describe('ViewsRail', () => {
});
it('saves the current filters as a named view from the dialog', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onViewSaved = jest.fn();
const props = renderRail({ onViewSaved });
@@ -163,24 +163,8 @@ describe('ViewsRail', () => {
);
});
it('shows the list placeholder in the save and rename dialogs', async () => {
const user = userEvent.setup();
renderRail({ viewNamePlaceholder: 'e.g. Prod things' });
await user.click(screen.getByTestId(`${PREFIX}-view-save-trigger`));
await expect(
screen.findByTestId('save-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
await user.click(screen.getByTestId('save-view-cancel'));
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
await expect(
screen.findByTestId('rename-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
});
it('opens the save dialog empty again after a cancel', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const props = renderRail({ isModified: true });
await user.click(screen.getByTestId(`${PREFIX}-view-save-as-new`));
@@ -199,7 +183,7 @@ describe('ViewsRail', () => {
});
it('renames a custom view from a dialog filled with its name', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onViewRenamed = jest.fn();
const props = renderRail({ onViewRenamed });
@@ -222,7 +206,7 @@ describe('ViewsRail', () => {
});
it('refills the rename dialog with the name of the view it opens for', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const props = renderRail();
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));

View File

@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log link from the ⋯ menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
});
it('copies the log from the ⋯ menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderDrawer();
@@ -128,7 +128,7 @@ describe('LogDetail drawer — header', () => {
});
it('keeps the drawer open when a ⋯ menu item is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -152,7 +152,7 @@ describe('LogDetail drawer — header', () => {
});
it('calls handleOpenInExplorer when "Open in Explorer" is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const handleOpenInExplorer = jest.fn();
renderDrawer({ handleOpenInExplorer });
@@ -163,7 +163,7 @@ describe('LogDetail drawer — header', () => {
});
it('closes from the close button and from Escape', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -176,7 +176,7 @@ describe('LogDetail drawer — header', () => {
});
it('closes on a mousedown outside the drawer and not on one inside it', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderDrawer({ onClose });
@@ -196,7 +196,7 @@ describe('LogDetail drawer — header', () => {
});
it('keeps the drawer open on a mousedown in a data-log-detail-ignore region', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
render(
@@ -258,7 +258,7 @@ describe('LogDetail drawer — header', () => {
});
it('navigates to the next / previous log with the Down / Up arrow keys', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const logs = [makeLog('log-0'), makeLog('log-1'), makeLog('log-2')];
const onNavigateLog = jest.fn();
const onScrollToLog = jest.fn();
@@ -276,7 +276,7 @@ describe('LogDetail drawer — header', () => {
});
it('does not navigate past the first log on ArrowUp', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const logs = [makeLog('log-0'), makeLog('log-1')];
const onNavigateLog = jest.fn();
@@ -287,7 +287,7 @@ describe('LogDetail drawer — header', () => {
});
it('navigates via the header up / down buttons and disables them at boundaries', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
const logs = [makeLog('log-0'), makeLog('log-1')];
const onNavigateLog = jest.fn();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
import { render, screen } from 'tests/test-utils';
import { render, screen } from '@testing-library/react';
import MessageTip from './index';
@@ -35,13 +35,13 @@ describe('MessageTip', () => {
// taken from antd docs
// https://github.com/ant-design/ant-design/blob/master/components/alert/__tests__/index.test.tsx
it('custom action', () => {
const { asFragment } = render(
const { container } = render(
<MessageTip
show
message="Success Tips"
action={<button type="button">Close</button>}
/>,
);
expect(asFragment()).toMatchSnapshot();
expect(container.firstChild).toMatchSnapshot();
});
});

View File

@@ -1,8 +1,7 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`MessageTip custom action 1`] = `
<DocumentFragment>
.c0 {
.c0 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
@@ -10,47 +9,46 @@ exports[`MessageTip custom action 1`] = `
}
<div
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
data-show="true"
role="alert"
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
data-show="true"
role="alert"
>
<span
aria-label="info-circle"
class="anticon anticon-info-circle ant-alert-icon"
role="img"
>
<span
aria-label="info-circle"
class="anticon anticon-info-circle ant-alert-icon"
role="img"
<svg
aria-hidden="true"
data-icon="info-circle"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<svg
aria-hidden="true"
data-icon="info-circle"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
/>
</svg>
</span>
<path
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
/>
</svg>
</span>
<div
class="ant-alert-content"
>
<div
class="ant-alert-content"
class="ant-alert-description"
>
<div
class="ant-alert-description"
>
Success Tips
</div>
</div>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
Success Tips
</div>
</div>
</DocumentFragment>
<div
class="ant-alert-action"
>
<button
type="button"
>
Close
</button>
</div>
</div>
`;

View File

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

View File

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

View File

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

View File

@@ -4,9 +4,8 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
} from '@testing-library/react';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -30,6 +29,9 @@ const mockOptions = [
{ label: 'Option 3', value: 'option3' },
];
// CSS selector for retry button
const RETRY_BUTTON_SELECTOR = '[data-testid="retry-button"]';
describe('CustomMultiSelect - Retry Functionality', () => {
beforeEach(() => {
jest.clearAllMocks();
@@ -59,7 +61,8 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Check that retry button (ReloadOutlined icon) is present
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
});
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
@@ -85,11 +88,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).not.toBeInTheDocument();
});
it('should call onRetry function when retry button is clicked', async () => {
const user = userEvent.setup();
const mockOnRetry = jest.fn();
const errorMessage = 'Internal Server Error (500)';
@@ -105,7 +108,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
// Open dropdown
const selectElement = screen.getByRole('combobox');
await user.click(selectElement);
fireEvent.mouseDown(selectElement);
// Wait for dropdown to appear
await waitFor(() => {
@@ -113,7 +116,10 @@ describe('CustomMultiSelect - Retry Functionality', () => {
});
// Find and click the retry button
await user.click(screen.getByTestId('retry-button'));
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
expect(retryButton).toBeInTheDocument();
fireEvent.click(retryButton as Element);
// Verify onRetry was called
expect(mockOnRetry).toHaveBeenCalledTimes(1);

View File

@@ -4,10 +4,9 @@ import {
render,
RenderResult,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -157,7 +156,6 @@ describe('CustomMultiSelect Component', () => {
});
it('removes a tag when clicked', async () => {
const user = userEvent.setup();
const handleChange = jest.fn();
renderWithVirtuoso(
<CustomMultiSelect
@@ -168,7 +166,10 @@ describe('CustomMultiSelect Component', () => {
);
// Find close button on Option 1 tag and click it
await user.click(screen.getByLabelText('Remove tag option1'));
const closeButtons = document.querySelectorAll(
'.ant-select-selection-item-remove',
);
fireEvent.click(closeButtons[0]);
// Verify onChange was called with remaining option
expect(handleChange).toHaveBeenCalledWith(
@@ -178,24 +179,39 @@ describe('CustomMultiSelect Component', () => {
});
it('filters options when searching', async () => {
const user = userEvent.setup();
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
// Open dropdown
const selectElement = screen.getByRole('combobox');
await user.click(selectElement);
fireEvent.mouseDown(selectElement);
// Type into search box - the combobox is the search input
await user.type(selectElement, '2');
// Type into search box - get input directly
const inputElement = selectElement.querySelector('input');
if (inputElement) {
fireEvent.change(inputElement, { target: { value: '2' } });
}
await waitFor(() =>
expect(screen.queryByTestId('option-item-option1')).not.toBeInTheDocument(),
);
expect(
within(screen.getByTestId('custom-multiselect-dropdown'))
.getAllByTestId(/^option-item-/)
.map((option) => option.dataset.testid),
).toStrictEqual(['option-item-2', 'option-item-option2']);
// Wait for the dropdown filtering to happen
await waitFor(() => {
// Check that the dropdown is present
const dropdownElement = document.querySelector(
'.custom-multiselect-dropdown',
);
expect(dropdownElement).toBeInTheDocument();
// Verify Option 2 is visible in the dropdown
const options = document.querySelectorAll('.option-label-text');
let foundOption2 = false;
options.forEach((option) => {
const text = option.textContent || '';
if (text.includes('Option 2')) {
foundOption2 = true;
}
});
expect(foundOption2).toBe(true);
});
});
it('renders grouped options correctly', async () => {

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,8 @@
import { act, render, screen, userEvent, within } from 'tests/test-utils';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import OverflowInputToolTip from './OverflowInputToolTip';
const TOOLTIP_INNER_SELECTOR = '.ant-tooltip-inner';
// Utility to mock overflow behaviour on inputs / elements.
// Stubs HTMLElement.prototype.clientWidth, scrollWidth and offsetWidth used by component.
function mockOverflow(clientWidth: number, scrollWidth: number): void {
@@ -21,17 +22,21 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
});
}
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
function queryTooltipInner(): HTMLElement | null {
// find element that has role="tooltip" (could be the inner itself)
const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');
if (!tooltip) {
return document.querySelector(TOOLTIP_INNER_SELECTOR);
}
async function hoverPastOpenDelay(element: HTMLElement): Promise<void> {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
await user.hover(element);
act(() => {
jest.advanceTimersByTime(ANTD_TOOLTIP_OPEN_DELAY_MS * 2);
});
// if the role element is already the inner, return it; otherwise return its descendant
if (tooltip.classList.contains('ant-tooltip-inner')) {
return tooltip;
}
return (
(tooltip.querySelector(TOOLTIP_INNER_SELECTOR) as HTMLElement) ??
document.querySelector(TOOLTIP_INNER_SELECTOR)
);
}
describe('OverflowInputToolTip', () => {
@@ -39,10 +44,6 @@ describe('OverflowInputToolTip', () => {
jest.restoreAllMocks();
});
afterEach(() => {
jest.useRealTimers();
});
it('shows tooltip when content overflows and input is clamped at maxAutoWidth', async () => {
mockOverflow(150, 250); // clientWidth >= maxAutoWidth (150), scrollWidth > clientWidth
@@ -50,9 +51,16 @@ describe('OverflowInputToolTip', () => {
await userEvent.hover(screen.getByRole('textbox'));
const tooltip = await screen.findByRole('tooltip');
await waitFor(() => {
expect(queryTooltipInner()).not.toBeNull();
});
const tooltipInner = queryTooltipInner();
if (!tooltipInner) {
throw new Error('Tooltip inner not found');
}
expect(
within(tooltip).getByText('Very long overflowing text'),
within(tooltipInner).getByText('Very long overflowing text'),
).toBeInTheDocument();
});
@@ -61,9 +69,11 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Short text" />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
@@ -71,9 +81,11 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Long but input not clamped" />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('uncontrolled input allows typing', async () => {
@@ -90,20 +102,24 @@ describe('OverflowInputToolTip', () => {
render(<OverflowInputToolTip value="Overflowing!" disabled />);
await hoverPastOpenDelay(screen.getByRole('textbox'));
await userEvent.hover(screen.getByRole('textbox'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
await waitFor(() => {
expect(queryTooltipInner()).toBeNull();
});
});
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
render(<OverflowInputToolTip value="Snapshot" />);
const mirror = screen.getByTestId('overflow-input-mirror');
const input = screen.getByRole('textbox');
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
const mirror = container.querySelector('.overflow-input-mirror');
const input = container.querySelector('input') as HTMLInputElement | null;
expect(mirror.textContent).toBe('Snapshot');
expect(input).toHaveValue('Snapshot');
expect(mirror).toBeTruthy();
expect(mirror?.textContent).toBe('Snapshot');
expect(input).toBeTruthy();
expect(input?.value).toBe('Snapshot');
// width should be set inline (component calculates width on mount)
expect(input.getAttribute('style')).toContain('width:');
expect(input?.getAttribute('style')).toContain('width:');
});
});

View File

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

View File

@@ -105,8 +105,6 @@ const stopEventsExtension = EditorView.domEventHandlers({
},
});
const EDITOR_BASIC_SETUP = { lineNumbers: false };
interface QuerySearchProps {
placeholder?: string;
onChange: (value: string) => void;
@@ -319,20 +317,23 @@ function QuerySearch({
500,
);
const toggleSuggestions = useCallback((timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (editorRef.current.hasFocus) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
const toggleSuggestions = useCallback(
(timeout?: number) => {
const timeoutId = setTimeout(() => {
if (!editorRef.current) {
return;
}
if (isFocused) {
startCompletion(editorRef.current);
} else {
closeCompletion(editorRef.current);
}
}, timeout);
return (): void => clearTimeout(timeoutId);
}, []);
return (): void => clearTimeout(timeoutId);
},
[isFocused],
);
const fetchKeySuggestions = useCallback(
async (searchText?: string): Promise<void> => {
@@ -715,17 +716,14 @@ function QuerySearch({
}
}, []);
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const handleChange = useCallback((value: string): void => {
const handleChange = (value: string): void => {
if (isProgrammaticChangeRef.current) {
isProgrammaticChangeRef.current = false;
return;
}
onChangeRef.current(value);
}, []);
onChange(value);
};
const handleBlur = (): void => {
const currentExpression = getCurrentExpression();
@@ -1479,65 +1477,6 @@ function QuerySearch({
};
}
const completionSourceRef = useRef(combinedSuggestions);
completionSourceRef.current = combinedSuggestions;
const handleRunRef = useRef(handleRun);
handleRunRef.current = handleRun;
// Built once: new extensions reconfigure CodeMirror, which closes the open suggestions.
const editorExtensions = useMemo(
() => [
autocompletion({
override: [
(context: CompletionContext): CompletionResult | null =>
completionSourceRef.current(context),
],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRunRef.current();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
],
[],
);
// Effect to handle focus state and trigger suggestions
useEffect(() => {
const clearTimeout = toggleSuggestions(10);
@@ -1658,10 +1597,7 @@ function QuerySearch({
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
{isScopedFilter && !showScopeChip ? (
<Tooltip title={initialExpression || ''} placement="left">
<div
className="query-search-initial-scope-label"
data-testid="query-search-initial-scope-label"
>
<div className="query-search-initial-scope-label">
<Filter
size={14}
style={{
@@ -1714,9 +1650,56 @@ function QuerySearch({
hasErrors: validation.errors.length > 0,
hasInitialExpression: isScopedFilter && !showScopeChip,
})}
extensions={editorExtensions}
extensions={[
autocompletion({
override: [combinedSuggestions],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRun();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
]}
placeholder={placeholder}
basicSetup={EDITOR_BASIC_SETUP}
basicSetup={{
lineNumbers: false,
}}
onFocus={(): void => {
setIsFocused(true);
}}

View File

@@ -168,7 +168,6 @@ export function renderRecentDeleteButton(
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'cm-recent-delete';
btn.dataset.testid = 'query-search-recent-delete';
btn.setAttribute('aria-label', 'Remove from recent searches');
btn.title = 'Remove from recent searches';
btn.textContent = '×';

View File

@@ -9,7 +9,7 @@ import {
import { ENVIRONMENT } from 'constants/env';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, within } from 'tests/test-utils';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import type {
IBuilderQuery,
Query,
@@ -19,7 +19,6 @@ import { EQueryType } from 'types/common/dashboard';
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findCompletionOption } from './findCompletionOption';
const EDITOR_TEST_ID = 'query-aggregation-editor';
// CodeMirror's suggestion popup is slow to open under a parallel jest run.
@@ -117,7 +116,7 @@ async function enterAggregation(
queryData: IBuilderQuery = aiQuery,
currentQuery?: Query,
): Promise<void> {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2Provider>
<QueryAggregationSelect queryData={queryData} />
@@ -126,9 +125,12 @@ async function enterAggregation(
{ queryBuilderOverrides: currentQuery && { currentQuery } },
);
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
'textbox',
);
const content = (
await screen.findByTestId(EDITOR_TEST_ID)
).querySelector<HTMLElement>('.cm-content');
if (!content) {
throw new Error('CodeMirror content element not rendered');
}
await user.click(content);
// Typed keys drop under load: a re-render's dispatch discards DOM input CodeMirror hasn't read yet.
await user.paste(text);
@@ -136,10 +138,10 @@ async function enterAggregation(
}
function suggestionLabels(): string[] {
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((option) => option.textContent ?? '')
.sort();
return Array.from(
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
(label) => label.textContent ?? '',
).sort();
}
describe('QueryAggregationSelect field suggestions for an AI query', () => {
@@ -159,10 +161,9 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
async ({ aggregation, fieldDataType, labels }) => {
await enterAggregation(aggregation);
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual(labels);
expect(keysRequests).toHaveLength(0);
expect(
aiKeysRequests.map((params) => ({
@@ -184,13 +185,14 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
);
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
timeout: SUGGESTIONS_TIMEOUT_MS,
});
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]);
await waitFor(
() =>
expect(suggestionLabels()).toStrictEqual([
'duration_nano',
'trace.total_tokens',
]),
{ timeout: SUGGESTIONS_TIMEOUT_MS },
);
expect(keysRequests).toHaveLength(0);
},
TEST_TIMEOUT_MS,

View File

@@ -1,14 +1,13 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { render, userEvent, waitFor } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findCompletionOption } from './findCompletionOption';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const EDITOR_TEST_ID = 'query-where-clause-editor';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
beforeAll(() => {
mockCodeMirrorDomApis();
@@ -111,7 +110,11 @@ async function renderAndType(text: string): Promise<HTMLElement> {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => {
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, text);
return editor;
@@ -125,26 +128,32 @@ async function typeKeyThenEnterOperatorContext(
): Promise<void> {
const editor = await renderAndType(key);
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
await waitFor(() => {
expect(visibleOptionLabels()).toContain(expectedKeyLabel);
});
// skipClick: a click would reset the caret to position 0 under the mocked
// DOM rects; we need the space appended at the end of the typed key.
await userEvent.type(editor, ' ', { skipClick: true });
await findCompletionOption(EDITOR_TEST_ID, '=');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('=');
});
}
function visibleOptionLabels(): string[] {
return within(screen.getByTestId(EDITOR_TEST_ID))
.queryAllByRole('option')
.map((el) => el.textContent ?? '');
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(
(el) => el.textContent ?? '',
);
}
describe('QuerySearch context-prefixed key suggestions', () => {
it('shows one deduped suggestion per key name in normal mode', async () => {
await renderAndType('statu');
await findCompletionOption(EDITOR_TEST_ID, 'status.code');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('status.code');
});
const statusOptions = visibleOptionLabels().filter(
(label) => label === 'status.code',
@@ -155,7 +164,9 @@ describe('QuerySearch context-prefixed key suggestions', () => {
it('shows context-scoped suggestions for a complete context prefix', async () => {
await renderAndType('attribute.');
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
await waitFor(() => {
expect(visibleOptionLabels()).toContain('attribute.status.code');
});
const labels = visibleOptionLabels();
// Literal key name match ranks first

View File

@@ -2,9 +2,7 @@ import { EditorView } from '@uiw/react-codemirror';
import { getFieldKeySuggestions } from 'api/querySuggestions/getFieldKeySuggestions';
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
import { initialQueriesMap } from 'constants/queryBuilder';
import { holdResponse } from 'tests/holdResponse';
import {
act,
fireEvent,
render,
screen,
@@ -16,9 +14,8 @@ import { DataSource } from 'types/common/queryBuilder';
import QuerySearch from '../QuerySearch/QuerySearch';
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
import { findQueryEditorTextbox } from './queryEditorTextbox';
const EDITOR_TEST_ID = 'query-where-clause-editor';
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
// Mock DOM APIs that CodeMirror needs
beforeAll(() => {
@@ -78,7 +75,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// CodeMirror renders a contenteditable div, so we check for the container
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
const editorContainer = document.querySelector('.query-where-clause-editor');
expect(editorContainer).toBeInTheDocument();
});
it('fetches key suggestions when typing a key (debounced)', async () => {
@@ -96,8 +94,14 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
// Wait for CodeMirror to initialize
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
// Find the CodeMirror editor contenteditable element
const editor = await findQueryEditorTextbox();
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
// Focus and type into the editor
await userEvent.click(editor);
@@ -137,7 +141,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
const editor = await findQueryEditorTextbox();
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
@@ -153,51 +162,6 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
await expect(screen.findByText('200')).resolves.toBeInTheDocument();
});
it('keeps the value suggestions open when the key suggestions load', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const { held, release } = holdResponse();
const mockedGetKeys = jest.mocked(getFieldKeySuggestions);
mockedGetKeys.mockClear();
mockedGetKeys.mockImplementationOnce(async () => {
await held;
return { status: 'success', data: { complete: true, keys: {} } };
});
jest.mocked(getFieldValueSuggestions).mockResolvedValueOnce({
status: 'success',
data: {
complete: true,
values: {
stringValues: ['payment-service'],
numberValues: [],
boolValues: [],
relatedValues: [],
},
},
});
render(
<QuerySearch
onChange={jest.fn()}
queryData={initialQueriesMap.logs.builder.queryData[0]}
dataSource={DataSource.LOGS}
/>,
);
const editor = await findQueryEditorTextbox();
await user.click(editor);
await user.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
await screen.findByText('payment-service');
await waitFor(() => expect(mockedGetKeys).toHaveBeenCalled());
release();
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
// Outlasts the 100 ms CodeMirror waits before it queries suggestions again.
await new Promise((resolve) => setTimeout(resolve, 150));
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<
@@ -239,7 +203,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize
const editor = await findQueryEditorTextbox();
await waitFor(() => {
const editor = document.querySelector(CM_EDITOR_SELECTOR);
expect(editor).toBeInTheDocument();
});
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
await userEvent.click(editor);
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
@@ -286,8 +255,11 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -296,7 +268,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
it('shows the locked scope as a chip in place of the scope icon', () => {
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
render(
const { container } = render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -311,12 +283,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
expect(chip).toHaveTextContent('+1');
expect(chip).not.toHaveTextContent('kind_string');
expect(
screen.queryByTestId('query-search-initial-scope-label'),
container.querySelector('.query-search-initial-scope-label'),
).not.toBeInTheDocument();
});
it('keeps the scope icon unless the chip is asked for', () => {
render(
const { container } = render(
<QuerySearch
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
queryData={initialQueriesMap.traces.builder.queryData[0]}
@@ -329,7 +301,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
screen.queryByTestId('query-search-scope-chip'),
).not.toBeInTheDocument();
expect(
screen.getByTestId('query-search-initial-scope-label'),
container.querySelector('.query-search-initial-scope-label'),
).toBeInTheDocument();
});
@@ -369,8 +341,11 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editor = await findQueryEditorTextbox();
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
await waitFor(() =>
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
SAMPLE_STATUS_QUERY,
),
);
await userEvent.click(screen.getByTestId('query-search-run-button'));
@@ -396,9 +371,13 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize and the expression to be set
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
// CodeMirror stores content in .cm-content, check the text content
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent).toBeInTheDocument();
// CodeMirror may render the text in multiple ways, check if it contains our expression
const textContent = editorContent.textContent || '';
expect(textContent).toContain('http.status_code');
@@ -433,9 +412,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
);
// Wait for CodeMirror to initialize with the initial expression
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent).toBeInTheDocument();
const textContent = editorContent.textContent || '';
expect(textContent).toBe(initialExpression);
},
@@ -495,9 +477,11 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
/>,
);
const editorContent = await findQueryEditorTextbox();
await waitFor(
() => {
const editorContent = document.querySelector(
CM_EDITOR_SELECTOR,
) as HTMLElement;
expect(editorContent.textContent || '').toBe(initialExpression);
},
{ timeout: 3000 },

View File

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

View File

@@ -1,14 +0,0 @@
import { screen, within, type waitForOptions } from 'tests/test-utils';
export function findCompletionOption(
editorTestId: string,
label: string,
options?: waitForOptions,
): Promise<HTMLElement> {
return within(screen.getByTestId(editorTestId)).findByText(
(_, element) =>
element?.getAttribute('role') === 'option' && element.textContent === label,
undefined,
options,
);
}

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
import { jest } from '@jest/globals';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { render, screen, userEvent, within } from 'tests/test-utils';
import { render, screen, userEvent } from 'tests/test-utils';
import {
Having,
IBuilderQuery,
@@ -146,7 +146,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
});
it('savePreviousQuery=true: metrics → meter saves previous query in session storage with appropriate key and query', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
panelType={PANEL_TYPES.TABLE}
@@ -155,9 +155,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
savePreviousQuery
/>,
);
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
await user.click(trigger);
@@ -182,7 +182,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
});
it('savePreviousQuery=false: metrics → meter does not write to sessionStorage and applies defaults', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
// render WITHOUT savePreviousQuery enabled
render(
<QueryBuilderV2
@@ -193,9 +193,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
);
// open Source and choose Meter
const trigger = within(
screen.getByTestId('metrics-source-selector-0'),
).getByRole('combobox');
const trigger = document.querySelector(
'.metrics-container .source-selector .ant-select-selector',
) as HTMLElement;
await user.click(trigger);
const meterOption = await screen.findByText('Meter');
await user.click(meterOption);
@@ -302,7 +302,7 @@ describe('DataSource change - Logs to Traces', () => {
});
it('updates query dataSource to TRACES saves previous query in session storage', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
@@ -313,12 +313,19 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
await user.click(logsTrigger);
await user.click(screen.getByTitle('Traces'));
const tracesContent = screen.getByText('Traces', {
selector: '.ant-select-item-option-content',
});
// click the option (prefer the option element; fallback to content)
await user.click(
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
);
// verify previousQuery store saved the current LOGS snapshot before switch
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
@@ -330,7 +337,7 @@ describe('DataSource change - Logs to Traces', () => {
);
});
it('updates query dataSource to TRACES does not saves previous query in session storage', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<QueryBuilderV2
@@ -340,12 +347,19 @@ describe('DataSource change - Logs to Traces', () => {
/>,
);
const logsTrigger = within(
screen.getByTestId('query-data-source-selector-0'),
).getByRole('combobox');
const logsTrigger = document.querySelector(
'.query-data-source .ant-select-selector',
) as HTMLElement;
await user.click(logsTrigger);
await user.click(screen.getByTitle('Traces'));
const tracesContent = screen.getByText('Traces', {
selector: '.ant-select-item-option-content',
});
// click the option (prefer the option element; fallback to content)
await user.click(
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
);
// Assert that no snapshot was written
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);

View File

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

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