mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-28 11:11:13 +00:00
Compare commits
30 Commits
ci/jest-te
...
perf/uplot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0fcaae2a8f | ||
|
|
05cf64aa34 | ||
|
|
ca10a4806e | ||
|
|
b1f271a505 | ||
|
|
c92bb94caf | ||
|
|
8e3a4f8775 | ||
|
|
a8433ad9e0 | ||
|
|
d07b0f1d82 | ||
|
|
a02330438f | ||
|
|
cb2b3db771 | ||
|
|
40ee169d94 | ||
|
|
865e1c97b3 | ||
|
|
5f24193de6 | ||
|
|
3d63ed6353 | ||
|
|
3af06adabc | ||
|
|
7b20abbeb7 | ||
|
|
73e6fa555a | ||
|
|
91525d721e | ||
|
|
251d49efce | ||
|
|
7d92c443b3 | ||
|
|
11cc323ca5 | ||
|
|
2d5a07048a | ||
|
|
6921b40467 | ||
|
|
d655a8998b | ||
|
|
70ab9c2321 | ||
|
|
e085decc05 | ||
|
|
415a74938b | ||
|
|
af3fd93339 | ||
|
|
22a65c4f74 | ||
|
|
fa1dbe25cb |
@@ -9,7 +9,7 @@ paths:
|
||||
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
|
||||
|
||||
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
|
||||
@@ -10,5 +10,6 @@
|
||||
- **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.
|
||||
|
||||
@@ -110,8 +110,9 @@ 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, and return early when the args take it 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. 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:
|
||||
|
||||
- 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.
|
||||
|
||||
16
.github/workflows/e2eci.yaml
vendored
16
.github/workflows/e2eci.yaml
vendored
@@ -184,22 +184,6 @@ 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
26
.github/workflows/flakyci.yaml
vendored
@@ -1,26 +0,0 @@
|
||||
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"
|
||||
12
.github/workflows/goci.yaml
vendored
12
.github/workflows/goci.yaml
vendored
@@ -63,7 +63,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: check-semconv-generated-files
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: qemu-install
|
||||
@@ -114,7 +114,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-openapi
|
||||
@@ -131,7 +131,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-authz
|
||||
@@ -148,7 +148,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-web-settings
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
- name: self-checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: go-install
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "1.25"
|
||||
- name: generate-transaction-groups
|
||||
|
||||
@@ -131,6 +131,10 @@ 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{}
|
||||
|
||||
@@ -296,6 +296,8 @@
|
||||
// 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",
|
||||
{
|
||||
@@ -316,6 +318,11 @@
|
||||
"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."
|
||||
@@ -338,6 +345,11 @@
|
||||
"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."
|
||||
@@ -552,6 +564,7 @@
|
||||
],
|
||||
"rules": {
|
||||
"import/first": "off",
|
||||
"signoz/no-dom-node-access": "error",
|
||||
// Should ignore due to mocks
|
||||
"signoz/no-navigator-clipboard": "off",
|
||||
// Tests can use navigator.clipboard directly,
|
||||
@@ -559,6 +572,8 @@
|
||||
"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
|
||||
@@ -615,6 +630,20 @@
|
||||
"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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
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.
|
||||
|
||||
@@ -21,7 +21,8 @@ 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/setup';
|
||||
import '../src/lib/monaco/loader';
|
||||
import '../src/lib/uPlotStylesheet';
|
||||
|
||||
import '../src/styles.scss';
|
||||
|
||||
@@ -176,6 +177,7 @@ const preview: Preview = {
|
||||
'AI Observability',
|
||||
['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],
|
||||
'Noz',
|
||||
['Overview', 'Modal', 'Panel'],
|
||||
'Metering',
|
||||
['Cost Meter', 'Usage Explorer'],
|
||||
'Messaging Queues',
|
||||
@@ -196,7 +198,9 @@ const preview: Preview = {
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
['Overview', 'Authz'],
|
||||
'Single Sign-on',
|
||||
['Overview', 'Authz'],
|
||||
'Keyboard Shortcuts',
|
||||
],
|
||||
'Auth',
|
||||
|
||||
@@ -157,7 +157,6 @@
|
||||
})(document, 'script');
|
||||
}
|
||||
</script>
|
||||
<link rel="stylesheet" href="css/uPlot.min.css" />
|
||||
<script type="module" src="./src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -11,9 +11,9 @@ const config: Config.InitialOptions = {
|
||||
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
|
||||
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
|
||||
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
|
||||
modulePathIgnorePatterns: ['dist'],
|
||||
modulePathIgnorePatterns: ['<rootDir>/dist/'],
|
||||
moduleNameMapper: {
|
||||
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
|
||||
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff|wav)$':
|
||||
'<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,9 +69,6 @@ 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,
|
||||
|
||||
@@ -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.0-rc.5",
|
||||
"@signozhq/ui": "0.4.1-rc.2",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
"@uiw/codemirror-theme-copilot": "4.23.11",
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
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 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
60
frontend/plugins/__tests__/no-dom-node-access.test.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ruleTester } from './rule-tester.mjs';
|
||||
|
||||
const message = (name) =>
|
||||
`Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`;
|
||||
|
||||
await ruleTester({
|
||||
rule: 'no-dom-node-access',
|
||||
valid: [
|
||||
{
|
||||
name: 'Testing Library queries',
|
||||
code: "within(screen.getByTestId('row')).getByText('Name');",
|
||||
},
|
||||
{
|
||||
name: 'a query method that is not called',
|
||||
code:
|
||||
'jest.spyOn(document, "querySelector");\nconst q = Element.prototype.closest;',
|
||||
},
|
||||
{
|
||||
name: 'computed access',
|
||||
code: "const name = 'closest';\nel[name]('tr');",
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
{
|
||||
name: 'querySelector on the container',
|
||||
code: "container.querySelector('.row');",
|
||||
errors: [{ message: message('querySelector'), line: 1, column: 11 }],
|
||||
},
|
||||
{
|
||||
name: 'closest after a screen query',
|
||||
code: "screen.getByText('Name').closest('tr');",
|
||||
errors: [{ message: message('closest'), line: 1, column: 26 }],
|
||||
},
|
||||
{
|
||||
name: 'optional call',
|
||||
code: "row?.querySelectorAll('td');",
|
||||
errors: [{ message: message('querySelectorAll'), line: 1, column: 6 }],
|
||||
},
|
||||
{
|
||||
name: 'traversal property',
|
||||
code: 'expect(cell.parentElement).toBeVisible();',
|
||||
errors: [{ message: message('parentElement'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a DOM node',
|
||||
code: "expect(screen.getByTestId('list').children).toHaveLength(2);",
|
||||
errors: [{ message: message('children'), line: 1, column: 35 }],
|
||||
},
|
||||
{
|
||||
name: 'children of a data tree',
|
||||
code: 'expect(tree.children).toHaveLength(2);',
|
||||
errors: [{ message: message('children'), line: 1, column: 13 }],
|
||||
},
|
||||
{
|
||||
name: 'document lookup by id',
|
||||
code: "document.getElementById('root');",
|
||||
errors: [{ message: message('getElementById'), line: 1, column: 10 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal file
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal file
@@ -0,0 +1,51 @@
|
||||
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' });
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
60
frontend/plugins/rules/no-dom-node-access.mjs
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Rule: no-dom-node-access
|
||||
*
|
||||
* Tests find elements through Testing Library (`screen`, `within`), not by
|
||||
* walking the DOM. Flags calls to DOM query methods and reads of node
|
||||
* traversal properties:
|
||||
* container.querySelector('.row')
|
||||
* screen.getByText('Name').closest('tr')
|
||||
* cell.parentElement
|
||||
* list.children
|
||||
*
|
||||
* A non-DOM `children` read (a data tree, React props) disables the rule on
|
||||
* that line with a reason.
|
||||
*/
|
||||
|
||||
const QUERY_METHODS = new Set([
|
||||
'querySelector',
|
||||
'querySelectorAll',
|
||||
'closest',
|
||||
'getElementById',
|
||||
'getElementsByClassName',
|
||||
'getElementsByTagName',
|
||||
'getElementsByName',
|
||||
]);
|
||||
|
||||
const TRAVERSAL_PROPERTIES = new Set([
|
||||
'parentElement',
|
||||
'parentNode',
|
||||
'firstChild',
|
||||
'lastChild',
|
||||
'firstElementChild',
|
||||
'lastElementChild',
|
||||
'nextSibling',
|
||||
'previousSibling',
|
||||
'nextElementSibling',
|
||||
'previousElementSibling',
|
||||
'childNodes',
|
||||
'children',
|
||||
]);
|
||||
|
||||
export default {
|
||||
create(context) {
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
if (node.computed || node.property.type !== 'Identifier') {
|
||||
return;
|
||||
}
|
||||
const { name } = node.property;
|
||||
const isCall =
|
||||
node.parent?.type === 'CallExpression' && node.parent.callee === node;
|
||||
if ((isCall && QUERY_METHODS.has(name)) || TRAVERSAL_PROPERTIES.has(name)) {
|
||||
context.report({
|
||||
node: node.property,
|
||||
message: `Find elements through Testing Library (\`screen\`, \`within\`) instead of \`${name}\`.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -19,6 +19,8 @@ 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: {
|
||||
@@ -39,5 +41,7 @@ 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,
|
||||
},
|
||||
};
|
||||
|
||||
10
frontend/pnpm-lock.yaml
generated
10
frontend/pnpm-lock.yaml
generated
@@ -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.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)
|
||||
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)
|
||||
'@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.0-rc.5':
|
||||
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
|
||||
'@signozhq/ui@0.4.1-rc.2':
|
||||
resolution: {integrity: sha512-pCMRzrJ6CmGjEgAQ2B6wRRengP2sy7Y860Npr5nkCapc9NPH5jy4VO48CDv5gnKwWSKShmLHwzbiK2E1cGndKQ==}
|
||||
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.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)':
|
||||
'@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)':
|
||||
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
1
frontend/public/css/uPlot.min.css
vendored
@@ -1 +0,0 @@
|
||||
.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;}
|
||||
@@ -117,6 +117,8 @@
|
||||
"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",
|
||||
|
||||
@@ -121,6 +121,8 @@
|
||||
"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",
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
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 <Empty> & 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>',
|
||||
);
|
||||
});
|
||||
@@ -1,43 +0,0 @@
|
||||
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'),
|
||||
);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
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, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
#!/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();
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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;
|
||||
@@ -1,110 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
|
||||
pathname === ROUTES.SETTINGS ||
|
||||
pathname === ROUTES.BILLING ||
|
||||
pathname === ROUTES.MEMBERS_SETTINGS ||
|
||||
(isAdmin &&
|
||||
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
|
||||
pathname === ROUTES.ORG_SETTINGS ||
|
||||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
|
||||
|
||||
if (
|
||||
pathname !== ROUTES.WORKSPACE_LOCKED &&
|
||||
|
||||
@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
|
||||
assertStaysOnRoute(ROUTES.BILLING);
|
||||
});
|
||||
|
||||
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
|
||||
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
|
||||
renderPrivateRoute({
|
||||
initialRoute: ROUTES.ORG_SETTINGS,
|
||||
appContext: {
|
||||
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
|
||||
isCloudUser: true,
|
||||
});
|
||||
|
||||
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
|
||||
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
|
||||
});
|
||||
|
||||
it('should allow VIEWER to access members settings when workspace is blocked', () => {
|
||||
@@ -1707,6 +1707,7 @@ 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: {
|
||||
|
||||
@@ -17,13 +17,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
@@ -15,13 +15,11 @@ function loadGetModule(href: string): GetModule {
|
||||
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
|
||||
mod = require('../get');
|
||||
});
|
||||
base.remove();
|
||||
return mod;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const el of document.head.querySelectorAll('base')) {
|
||||
el.remove();
|
||||
}
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
|
||||
BIN
frontend/src/assets/sounds/noz-reply.wav
Normal file
BIN
frontend/src/assets/sounds/noz-reply.wav
Normal file
Binary file not shown.
@@ -1,4 +1,4 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { act, render, screen } from 'tests/test-utils';
|
||||
|
||||
import LabelColumn from './LabelColumn';
|
||||
|
||||
@@ -92,7 +92,9 @@ describe('LabelColumn', () => {
|
||||
renderWithProviders(<LabelColumn labels={labels} />);
|
||||
|
||||
const isHidden = (label: string): boolean =>
|
||||
screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
|
||||
screen
|
||||
.getByTestId(`label-tag-container-${label}`)
|
||||
.classList.contains('overflowed');
|
||||
|
||||
expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
|
||||
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
|
||||
@@ -157,8 +159,7 @@ describe('LabelColumn', () => {
|
||||
it('should render empty when no labels provided', () => {
|
||||
renderWithProviders(<LabelColumn labels={[]} />);
|
||||
|
||||
const column = screen.getByTestId('label-column');
|
||||
expect(column.children).toHaveLength(0);
|
||||
expect(screen.getByTestId('label-column')).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('should use primary color by default', () => {
|
||||
|
||||
@@ -45,7 +45,7 @@ function LabelTag({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<span className={className}>
|
||||
<span className={className} data-testid={`label-tag-container-${label}`}>
|
||||
<Badge
|
||||
textTransform="none"
|
||||
color={color ?? 'secondary'}
|
||||
|
||||
@@ -22,7 +22,10 @@ function AppLoading(): JSX.Element {
|
||||
const isDarkMode = getThemeFromStorage();
|
||||
|
||||
return (
|
||||
<div className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}>
|
||||
<div
|
||||
className={`app-loading-container ${isDarkMode ? 'dark' : 'lightMode'}`}
|
||||
data-testid="app-loading-container"
|
||||
>
|
||||
<div className="perilin-bg" />
|
||||
<div className="app-loading-content">
|
||||
<div className="brand">
|
||||
@@ -53,7 +56,7 @@ function AppLoading(): JSX.Element {
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="loader" />
|
||||
<div className="loader" data-testid="app-loading-loader" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { screen } from 'tests/test-utils';
|
||||
|
||||
import getLocal from '../../../api/browser/localstorage/get';
|
||||
import AppLoading from '../AppLoading';
|
||||
@@ -15,7 +16,6 @@ describe('AppLoading', () => {
|
||||
const SIGNOZ_TEXT = 'SigNoz';
|
||||
const TAGLINE_TEXT =
|
||||
'OpenTelemetry-Native Logs, Metrics and Traces in a single pane';
|
||||
const CONTAINER_SELECTOR = '.app-loading-container';
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -33,7 +33,7 @@ describe('AppLoading', () => {
|
||||
expect(screen.getByText(TAGLINE_TEXT)).toBeInTheDocument();
|
||||
|
||||
// Check if dark theme class is applied
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
expect(container).not.toHaveClass('lightMode');
|
||||
});
|
||||
@@ -58,7 +58,7 @@ describe('AppLoading', () => {
|
||||
expect(tagline).toBeInTheDocument();
|
||||
|
||||
// Check for loader
|
||||
const loader = document.querySelector('.loader');
|
||||
const loader = screen.getByTestId('app-loading-loader');
|
||||
expect(loader).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -72,7 +72,7 @@ describe('AppLoading', () => {
|
||||
|
||||
// Should still render with dark theme as fallback
|
||||
expect(screen.getByText(SIGNOZ_TEXT)).toBeInTheDocument();
|
||||
const container = screen.getByText(SIGNOZ_TEXT).closest(CONTAINER_SELECTOR);
|
||||
const container = screen.getByTestId('app-loading-container');
|
||||
expect(container).toHaveClass('dark');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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="bottom-right" pageInset={PAGE_INSET} />;
|
||||
return <Toaster position="top-right" pageInset={PAGE_INSET} />;
|
||||
}
|
||||
|
||||
export default AppToaster;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
.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;
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
.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;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useEffect } from 'react';
|
||||
import { useMutation } from 'react-query';
|
||||
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
|
||||
import { Button, Modal } from 'antd';
|
||||
import Flex from 'periscope/components/Flex/Flex';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Dialog } from '@signozhq/ui/dialog';
|
||||
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';
|
||||
@@ -13,8 +12,9 @@ import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
|
||||
import { UserPreference } from 'types/api/preferences/preference';
|
||||
|
||||
import ChangelogRenderer from './components/ChangelogRenderer';
|
||||
import { useChangelogScroll } from './useChangelogScroll';
|
||||
|
||||
import './ChangelogModal.styles.scss';
|
||||
import styles from './ChangelogModal.module.scss';
|
||||
|
||||
interface Props {
|
||||
changelog: ChangelogSchema;
|
||||
@@ -22,8 +22,7 @@ interface Props {
|
||||
}
|
||||
|
||||
function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
|
||||
const [hasScroll, setHasScroll] = useState(false);
|
||||
const changelogContentSectionRef = useRef<HTMLDivElement>(null);
|
||||
const { contentRef, hasScroll, scrollForMore } = useChangelogScroll();
|
||||
const { userPreferences, updateUserPreferenceInContext } = useAppContext();
|
||||
|
||||
const formattedReleaseDate = dayjs(changelog?.release_date).format(
|
||||
@@ -57,30 +56,6 @@ 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',
|
||||
@@ -89,75 +64,61 @@ 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 (
|
||||
<Modal
|
||||
className={cx('changelog-modal')}
|
||||
title={
|
||||
<div className="changelog-modal-title">
|
||||
<ScrollText size={16} />
|
||||
What’s New ⎯ Changelog : {formattedReleaseDate}
|
||||
</div>
|
||||
}
|
||||
width={820}
|
||||
<Dialog
|
||||
open
|
||||
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>
|
||||
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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="changelog-modal-content"
|
||||
data-testid="changelog-content"
|
||||
ref={changelogContentSectionRef}
|
||||
>
|
||||
{changelog && <ChangelogRenderer changelog={changelog} />}
|
||||
<div data-testid="changelog-content" ref={contentRef}>
|
||||
<ChangelogRenderer changelog={changelog} />
|
||||
</div>
|
||||
</Modal>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
/* eslint-disable @typescript-eslint/explicit-function-return-type */
|
||||
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
|
||||
import { IAppContext } from 'providers/App/types';
|
||||
import {
|
||||
fireEvent,
|
||||
getAppContextMock,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from 'tests/test-utils';
|
||||
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';
|
||||
|
||||
@@ -40,71 +51,165 @@ const mockChangelog: ChangelogSchema = {
|
||||
jest.mock(
|
||||
'react-markdown',
|
||||
() =>
|
||||
function ReactMarkdown({ children }: any) {
|
||||
function ReactMarkdown({ children }: { children: ReactNode }): JSX.Element {
|
||||
return <div>{children}</div>;
|
||||
},
|
||||
);
|
||||
// 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 {
|
||||
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(
|
||||
<MockQueryClientProvider>
|
||||
<ChangelogModal changelog={mockChangelog} onClose={onClose} />
|
||||
</MockQueryClientProvider>,
|
||||
<ChangelogModal changelog={mockChangelog} onClose={onClose} />,
|
||||
undefined,
|
||||
{
|
||||
appContextOverrides: {
|
||||
userPreferences: [seenChangelogVersion],
|
||||
...appContextOverrides,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe('ChangelogModal', () => {
|
||||
it('renders modal with changelog data', () => {
|
||||
it('renders the dialog with the changelog data', async () => {
|
||||
renderChangelog();
|
||||
expect(
|
||||
screen.getByText('What’s New ⎯ Changelog : June 10, 2025'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
await expect(
|
||||
screen.findByTestId('changelog-dialog-title'),
|
||||
).resolves.toHaveTextContent('What’s New ⎯ Changelog : June 10, 2025');
|
||||
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 Skip for now is clicked', () => {
|
||||
it('calls onClose when the close button is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const onClose = jest.fn();
|
||||
renderChangelog(onClose);
|
||||
fireEvent.click(screen.getByText('Skip for now'));
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
|
||||
await user.click(await screen.findByTestId('changelog-dialog-close'));
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('opens migration docs when Update my workspace is clicked', () => {
|
||||
window.open = jest.fn();
|
||||
it('offers no upgrade actions to a cloud workspace', async () => {
|
||||
renderChangelog();
|
||||
fireEvent.click(screen.getByText('Update my workspace'));
|
||||
expect(window.open).toHaveBeenCalledWith(
|
||||
|
||||
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(
|
||||
'https://signoz.io/upgrade-path',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
);
|
||||
open.mockRestore();
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
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(),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
&-line {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
left: 3px;
|
||||
top: 6px;
|
||||
bottom: -30px;
|
||||
width: 1px;
|
||||
|
||||
52
frontend/src/components/ChangelogModal/useChangelogScroll.ts
Normal file
52
frontend/src/components/ChangelogModal/useChangelogScroll.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
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 };
|
||||
}
|
||||
@@ -68,7 +68,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('submit button becomes disabled after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -86,7 +86,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('successful submit shows toast.success and closes modal', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
@@ -112,7 +112,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('pressing Enter again while creating sends one request', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
let requests = 0;
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) => {
|
||||
@@ -146,7 +146,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows toast.error on API error and keeps modal open', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
server.use(
|
||||
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
|
||||
@@ -186,7 +186,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('Cancel button closes modal without submitting', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const cancelBtn = await screen.findByTestId('create-sa-cancel-btn');
|
||||
@@ -217,7 +217,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('keeps the footer usable when create permission is denied', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
server.use(setupAuthzDenyAll());
|
||||
|
||||
renderModal();
|
||||
@@ -242,7 +242,7 @@ describe('CreateServiceAccountModal', () => {
|
||||
});
|
||||
|
||||
it('shows "Name is required" after clearing the name field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderModal();
|
||||
|
||||
const nameInput = await screen.findByTestId('create-sa-name-input-field');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { fireEvent, screen, userEvent } from 'tests/test-utils';
|
||||
import dayjs from 'dayjs';
|
||||
import { mockAppLocation } from 'tests/router-mocks';
|
||||
import * as timeUtils from 'utils/timeUtils';
|
||||
@@ -157,7 +158,8 @@ describe('CustomTimePicker', () => {
|
||||
expect(onValid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats close after change like pressing Enter (blur + chevron)', () => {
|
||||
it('treats close after change like pressing Enter (blur + chevron)', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onValid = jest.fn();
|
||||
const onError = jest.fn();
|
||||
|
||||
@@ -166,16 +168,13 @@ describe('CustomTimePicker', () => {
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
// Open and change value so "changed since open" is true
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: '5m' } });
|
||||
fireEvent.blur(input);
|
||||
await user.click(input);
|
||||
await user.clear(input);
|
||||
await user.type(input, '5m');
|
||||
await user.tab();
|
||||
|
||||
// Click the chevron (which triggers handleClose)
|
||||
const chevron = document.querySelector(
|
||||
'.time-input-suffix-icon-badge',
|
||||
) as HTMLElement;
|
||||
|
||||
fireEvent.click(chevron);
|
||||
await user.click(screen.getByTestId('time-picker-close-chevron'));
|
||||
|
||||
// Should have applied the value (same as Enter)
|
||||
expect(onValid).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -640,12 +640,14 @@ function CustomTimePicker({
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleClose}
|
||||
data-testid="time-picker-close-chevron"
|
||||
/>
|
||||
) : (
|
||||
<ChevronDown
|
||||
size={14}
|
||||
className="cursor-pointer time-input-suffix-icon-badge"
|
||||
onClick={handleOpen}
|
||||
data-testid="time-picker-open-chevron"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -273,7 +273,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('enables Save after editing name and calls updateUser on confirm', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
@@ -306,7 +306,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('does not close the drawer after a successful save', async () => {
|
||||
const onClose = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
|
||||
@@ -331,7 +331,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('adding a new role creates a user role without removing existing ones', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockSet = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useCreateUserRole as jest.Mock).mockReturnValue({
|
||||
@@ -365,7 +365,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('deselecting a role deletes the user role by its assignment id', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer({ onComplete });
|
||||
|
||||
@@ -392,7 +392,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('shows delete confirm dialog and calls deleteUser for active members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -553,7 +553,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls deleteUser after confirming revoke invite for invited members', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -583,7 +583,7 @@ describe('EditMemberDrawer', () => {
|
||||
|
||||
it('calls updateUser when saving name change for an invited member', async () => {
|
||||
const onComplete = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockMutateAsync = jest.fn().mockResolvedValue({});
|
||||
|
||||
(useGetUser as jest.Mock).mockReturnValue({
|
||||
@@ -641,7 +641,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows SaveErrorItem when updateUser fails for name change', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useUpdateUser as jest.Mock).mockReturnValue({
|
||||
mutateAsync: jest.fn().mockRejectedValue(new Error('server error')),
|
||||
@@ -669,7 +669,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for active member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -700,7 +700,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('shows API error message when deleteUser fails for invited member', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
(useDeleteUser as jest.Mock).mockImplementation((options) => ({
|
||||
mutateAsync: mockDeleteMutate.mockImplementation(() => {
|
||||
@@ -740,7 +740,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (isSelf)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -811,7 +811,7 @@ describe('EditMemberDrawer', () => {
|
||||
isLoading: false,
|
||||
});
|
||||
server.use(setupAuthzDeny(buildUserUpdatePermission(selfMember.id)));
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer({ member: selfMember });
|
||||
|
||||
const input = await screen.findByDisplayValue('Alice Smith');
|
||||
@@ -875,7 +875,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not open delete confirm dialog when Delete is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /delete member/i }));
|
||||
@@ -886,7 +886,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('does not call createResetPasswordToken when Reset Link is clicked while disabled (root)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderDrawer();
|
||||
|
||||
await user.click(
|
||||
@@ -903,7 +903,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('calls POST and opens the reset link dialog with the generated link and expiry', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -925,7 +925,7 @@ describe('EditMemberDrawer', () => {
|
||||
});
|
||||
|
||||
it('copies the link to clipboard and shows "Copied!" on the button', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const mockToast = jest.mocked(toast);
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('ErrorModal Component', () => {
|
||||
|
||||
// Click the close button
|
||||
const closeButton = screen.getByTestId('close-button');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(closeButton);
|
||||
|
||||
// Check if onClose was called
|
||||
@@ -145,7 +145,7 @@ it('should open the modal when the trigger component is clicked', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('Open Error Modal');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
// Check if the modal is displayed
|
||||
@@ -165,12 +165,13 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
// Click the trigger component
|
||||
const triggerButton = screen.getByText('error');
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
await user.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('An error occurred')).toBeInTheDocument();
|
||||
});
|
||||
const modal = screen.getByRole('dialog');
|
||||
|
||||
// Trigger the onCancel event
|
||||
await user.click(screen.getByTestId('close-button'));
|
||||
@@ -180,8 +181,6 @@ it('should close the modal when the onCancel event is triggered', async () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// check if the modal is not visible
|
||||
const modal = document.getElementsByClassName('ant-modal');
|
||||
const style = window.getComputedStyle(modal[0]);
|
||||
expect(style.display).toBe('none');
|
||||
expect(modal).toHaveStyle({ display: 'none' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider } from 'react-redux';
|
||||
import { act, render, renderHook } from '@testing-library/react';
|
||||
import { act, render, renderHook } from 'tests/test-utils';
|
||||
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
|
||||
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
|
||||
import { useGlobalTimeStore } from 'store/globalTime/globalTimeStore';
|
||||
@@ -42,13 +42,13 @@ describe('GlobalTimeStoreAdapter', () => {
|
||||
globalTime: createGlobalTimeState(),
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<Provider store={store}>
|
||||
<GlobalTimeStoreAdapter />
|
||||
</Provider>,
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
expect(asFragment().hasChildNodes()).toBe(false);
|
||||
});
|
||||
|
||||
it('should sync relative time from Redux to Zustand store', () => {
|
||||
|
||||
@@ -2,8 +2,14 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
function AnnouncementsModal(): JSX.Element {
|
||||
return (
|
||||
<div className="announcements-modal-container">
|
||||
<div className="announcements-modal-container-header">
|
||||
<div
|
||||
className="announcements-modal-container"
|
||||
data-testid="announcements-modal"
|
||||
>
|
||||
<div
|
||||
className="announcements-modal-container-header"
|
||||
data-testid="announcements-modal-header"
|
||||
>
|
||||
<Typography
|
||||
variant="paragraph"
|
||||
size="base"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import AnnouncementsModal from '../AnnouncementsModal';
|
||||
|
||||
@@ -12,15 +12,14 @@ describe('AnnouncementsModal', () => {
|
||||
it('should have proper structure and classes', () => {
|
||||
render(<AnnouncementsModal />);
|
||||
|
||||
const container = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container');
|
||||
expect(container).toBeInTheDocument();
|
||||
const container = screen.getByTestId('announcements-modal');
|
||||
expect(container).toHaveClass('announcements-modal-container');
|
||||
|
||||
const headerContainer = screen
|
||||
.getByText('Announcements')
|
||||
.closest('.announcements-modal-container-header');
|
||||
expect(headerContainer).toBeInTheDocument();
|
||||
const headerContainer = within(container).getByTestId(
|
||||
'announcements-modal-header',
|
||||
);
|
||||
expect(headerContainer).toHaveClass('announcements-modal-container-header');
|
||||
expect(headerContainer).toHaveTextContent('Announcements');
|
||||
});
|
||||
|
||||
it('should render without any errors', () => {
|
||||
|
||||
@@ -64,7 +64,10 @@ function InviteMembers({
|
||||
const hasSuccesses = successResults.length > 0;
|
||||
|
||||
return (
|
||||
<div className={cx(styles.inviteMembers, className)}>
|
||||
<div
|
||||
className={cx(styles.inviteMembers, className)}
|
||||
data-testid="invite-members"
|
||||
>
|
||||
<div className={styles.table}>
|
||||
{showHeader && (
|
||||
<div className={styles.header}>
|
||||
|
||||
@@ -66,9 +66,9 @@ describe('InviteMembers - Rendering', () => {
|
||||
});
|
||||
|
||||
it('applies custom className', () => {
|
||||
const { container } = render(<InviteMembers className="custom-class" />);
|
||||
render(<InviteMembers className="custom-class" />);
|
||||
|
||||
expect(container.querySelector('.custom-class')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('invite-members')).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('renders footer via renderFooter prop', () => {
|
||||
|
||||
@@ -15,7 +15,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('adds a row when "Add another" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -27,7 +27,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('removes a row when trash button is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
@@ -40,7 +40,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('respects minRows constraint when removing rows', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} minRows={2} />);
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('cannot remove rows below minRows=1 default', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={2} />);
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('InviteMembers - Row Management', () => {
|
||||
});
|
||||
|
||||
it('preserves data in other rows when removing one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(<InviteMembers initialRowCount={3} />);
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('email validation', () => {
|
||||
it('shows email validation error when email is invalid and role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -46,7 +46,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('shows inline error for invalid email field', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -70,7 +70,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears validation error when email is corrected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -104,7 +104,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('role validation', () => {
|
||||
it('shows role validation error when role is missing', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -127,7 +127,7 @@ describe('InviteMembers - Validation', () => {
|
||||
});
|
||||
|
||||
it('clears role validation error when role is selected', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -159,7 +159,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('combined validation', () => {
|
||||
it('shows combined error when both email and role are invalid', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
@@ -186,7 +186,7 @@ describe('InviteMembers - Validation', () => {
|
||||
|
||||
describe('touched rows', () => {
|
||||
it('only validates touched rows (rows with email or role)', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
|
||||
@@ -14,14 +14,14 @@ export type CreatedByProps =
|
||||
creatorOptions: CreatorOption[];
|
||||
createdBy: string[];
|
||||
onCreatedByChange: (emails: string[]) => void;
|
||||
// Clear all Created-by selections and run immediately.
|
||||
onClearCreatedBy: () => void;
|
||||
// Run a Created-by change made with the dropdown closed.
|
||||
onCreatedByCommit: (emails: string[]) => void;
|
||||
}
|
||||
| {
|
||||
creatorOptions?: undefined;
|
||||
createdBy?: undefined;
|
||||
onCreatedByChange?: undefined;
|
||||
onClearCreatedBy?: undefined;
|
||||
onCreatedByCommit?: 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}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -81,7 +81,7 @@ function FilterZone({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleClearCreatedBy,
|
||||
handleCreatedByCommit,
|
||||
handleClear,
|
||||
} = useFilterZoneDraft({
|
||||
query,
|
||||
@@ -96,7 +96,7 @@ function FilterZone({
|
||||
creatorOptions,
|
||||
createdBy: reflected.createdBy,
|
||||
onCreatedByChange: handleCreatedByChange,
|
||||
onClearCreatedBy: handleClearCreatedBy,
|
||||
onCreatedByCommit: handleCreatedByCommit,
|
||||
}
|
||||
: {};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { ConfigProvider, Select } from 'antd';
|
||||
import { Checkbox } from '@signozhq/ui/checkbox';
|
||||
import cx from 'classnames';
|
||||
@@ -20,7 +21,9 @@ interface Props {
|
||||
placeholder: string;
|
||||
testId: string;
|
||||
onChange: (values: string[]) => void;
|
||||
onClear?: () => 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;
|
||||
onDropdownVisibleChange?: (open: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
@@ -31,10 +34,31 @@ function MultiSelectFilter({
|
||||
placeholder,
|
||||
testId,
|
||||
onChange,
|
||||
onClear,
|
||||
onCommit,
|
||||
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
|
||||
@@ -51,7 +75,6 @@ function MultiSelectFilter({
|
||||
menuItemSelectedIcon={null}
|
||||
data-testid={testId}
|
||||
disabled={disabled}
|
||||
onClear={onClear}
|
||||
optionRender={(option): JSX.Element => (
|
||||
<div
|
||||
className={styles.checkOption}
|
||||
@@ -66,8 +89,8 @@ function MultiSelectFilter({
|
||||
<span className={styles.checkOptionLabel}>{option.label}</span>
|
||||
</div>
|
||||
)}
|
||||
onChange={(next): void => onChange(next as string[])}
|
||||
onDropdownVisibleChange={onDropdownVisibleChange}
|
||||
onChange={(next): void => handleChange(next as string[])}
|
||||
onDropdownVisibleChange={handleDropdownVisibleChange}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import FilterZone from '../FilterZone';
|
||||
@@ -47,4 +48,33 @@ 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('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -106,12 +106,20 @@ describe('useFilterZoneDraft', () => {
|
||||
"created_by = 'a@x.io' AND name = 'x'",
|
||||
);
|
||||
|
||||
act(() => result.current.handleClearCreatedBy());
|
||||
act(() => result.current.handleCreatedByCommit([]));
|
||||
|
||||
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();
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ interface FilterZoneDraft {
|
||||
applyDraft: (next: string) => void;
|
||||
handleCreatedByChange: (emails: string[]) => void;
|
||||
handleUpdatedChange: (window: UpdatedWindow) => void;
|
||||
handleClearCreatedBy: () => void;
|
||||
handleCreatedByCommit: (emails: string[]) => void;
|
||||
handleClear: () => void;
|
||||
}
|
||||
|
||||
@@ -97,10 +97,14 @@ export function useFilterZoneDraft({
|
||||
[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]);
|
||||
// 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 resets the draft and runs immediately (empty query).
|
||||
const handleClear = useCallback((): void => {
|
||||
@@ -122,7 +126,7 @@ export function useFilterZoneDraft({
|
||||
applyDraft,
|
||||
handleCreatedByChange,
|
||||
handleUpdatedChange,
|
||||
handleClearCreatedBy,
|
||||
handleCreatedByCommit,
|
||||
handleClear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ describe('InvalidQueryState', () => {
|
||||
});
|
||||
|
||||
it('runs the callback, then opens support', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onContactSupport = jest.fn();
|
||||
render(
|
||||
<InvalidQueryState
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import type { DslGrammar } from '../../dsl/types';
|
||||
import SearchBar from '../SearchBar';
|
||||
@@ -40,9 +40,7 @@ function renderSearchBar(props: { dirty: boolean; disabled?: boolean }): {
|
||||
}
|
||||
|
||||
function searchContent(): HTMLElement {
|
||||
return screen
|
||||
.getByTestId('list-search')
|
||||
.querySelector('.cm-content') as HTMLElement;
|
||||
return within(screen.getByTestId('list-search')).getByRole('textbox');
|
||||
}
|
||||
|
||||
describe('SearchBar — run on blur', () => {
|
||||
|
||||
@@ -24,6 +24,7 @@ interface Props {
|
||||
confirmLabel: string;
|
||||
/** Name the input holds each time the dialog opens. */
|
||||
initialName?: string;
|
||||
placeholder: string;
|
||||
testIdPrefix: string;
|
||||
}
|
||||
|
||||
@@ -35,6 +36,7 @@ function ViewNameDialog({
|
||||
description,
|
||||
confirmLabel,
|
||||
initialName = '',
|
||||
placeholder,
|
||||
testIdPrefix,
|
||||
}: Props): JSX.Element {
|
||||
const [name, setName] = useState(initialName);
|
||||
@@ -116,7 +118,7 @@ function ViewNameDialog({
|
||||
id={inputId}
|
||||
value={name}
|
||||
maxLength={VIEW_NAME_MAX_LENGTH}
|
||||
placeholder="e.g. Prod alerts"
|
||||
placeholder={placeholder}
|
||||
autoComplete="off"
|
||||
testId={`${testIdPrefix}-name`}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>): void =>
|
||||
|
||||
@@ -39,6 +39,7 @@ 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;
|
||||
@@ -67,6 +68,7 @@ function ViewsRail({
|
||||
saveTestIdPrefix = 'save-view',
|
||||
renameTestIdPrefix = 'rename-view',
|
||||
customSectionLabel = 'My views',
|
||||
viewNamePlaceholder = 'e.g. Production',
|
||||
deleteDescription = 'This removes the saved view.',
|
||||
guard,
|
||||
onViewSaved,
|
||||
@@ -287,6 +289,7 @@ 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
|
||||
@@ -297,6 +300,7 @@ function ViewsRail({
|
||||
description="The view keeps its filters under the new name."
|
||||
confirmLabel="Rename"
|
||||
initialName={renameTarget?.label}
|
||||
placeholder={viewNamePlaceholder}
|
||||
testIdPrefix={renameTestIdPrefix}
|
||||
/>
|
||||
{contextHolder}
|
||||
|
||||
@@ -52,7 +52,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('selects a view by id', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-view-2`));
|
||||
@@ -61,7 +61,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('filters views by name and says when none match', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
renderRail();
|
||||
const search = screen.getByTestId(`${PREFIX}-view-search-field`);
|
||||
|
||||
@@ -109,7 +109,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('offers save, save as and reset for a modified custom view', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({
|
||||
activeViewId: 'view-1',
|
||||
@@ -138,7 +138,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('saves the current filters as a named view from the dialog', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewSaved = jest.fn();
|
||||
const props = renderRail({ onViewSaved });
|
||||
|
||||
@@ -163,8 +163,24 @@ 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({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail({ isModified: true });
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-save-as-new`));
|
||||
@@ -183,7 +199,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('renames a custom view from a dialog filled with its name', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onViewRenamed = jest.fn();
|
||||
const props = renderRail({ onViewRenamed });
|
||||
|
||||
@@ -206,7 +222,7 @@ describe('ViewsRail', () => {
|
||||
});
|
||||
|
||||
it('refills the rename dialog with the name of the view it opens for', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const props = renderRail();
|
||||
|
||||
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
|
||||
|
||||
@@ -104,7 +104,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log link from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('copies the log from the ⋯ menu', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
renderDrawer();
|
||||
|
||||
@@ -128,7 +128,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open when a ⋯ menu item is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -152,7 +152,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('calls handleOpenInExplorer when "Open in Explorer" is clicked', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const handleOpenInExplorer = jest.fn();
|
||||
|
||||
renderDrawer({ handleOpenInExplorer });
|
||||
@@ -163,7 +163,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes from the close button and from Escape', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -176,7 +176,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('closes on a mousedown outside the drawer and not on one inside it', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
renderDrawer({ onClose });
|
||||
@@ -196,7 +196,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('keeps the drawer open on a mousedown in a data-log-detail-ignore region', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const onClose = jest.fn();
|
||||
|
||||
render(
|
||||
@@ -258,7 +258,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates to the next / previous log with the Down / Up arrow keys', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1'), makeLog('log-2')];
|
||||
const onNavigateLog = jest.fn();
|
||||
const onScrollToLog = jest.fn();
|
||||
@@ -276,7 +276,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('does not navigate past the first log on ArrowUp', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
@@ -287,7 +287,7 @@ describe('LogDetail drawer — header', () => {
|
||||
});
|
||||
|
||||
it('navigates via the header up / down buttons and disables them at boundaries', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const logs = [makeLog('log-0'), makeLog('log-1')];
|
||||
const onNavigateLog = jest.fn();
|
||||
|
||||
|
||||
@@ -1,46 +1,39 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { render, screen, within } from 'tests/test-utils';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
|
||||
import LogStateIndicator from './LogStateIndicator';
|
||||
|
||||
describe('LogStateIndicator', () => {
|
||||
it('renders correctly with default props', () => {
|
||||
const { container } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
render(<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />);
|
||||
const indicator = screen.getByTestId('log-state-indicator');
|
||||
expect(indicator).toHaveClass('log-state-indicator');
|
||||
expect(indicator).not.toHaveClass('isActive');
|
||||
expect(within(indicator).getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator.classList.contains('log-state-indicator')).toBe(true);
|
||||
expect(indicator.classList.contains('isActive')).toBe(false);
|
||||
expect(container.querySelector('.line')).toBeTruthy();
|
||||
expect(
|
||||
container.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('renders correctly with different types', () => {
|
||||
const { container: containerInfo } = render(
|
||||
const { rerender } = render(
|
||||
<LogStateIndicator severityText="INFO" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerInfo.querySelector('.line')?.classList.contains('severity-info-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-info-0',
|
||||
);
|
||||
|
||||
const { container: containerWarning } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="WARNING" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerWarning
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-warn-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-warn-0',
|
||||
);
|
||||
|
||||
const { container: containerError } = render(
|
||||
rerender(
|
||||
<LogStateIndicator severityText="ERROR" fontSize={FontSize.MEDIUM} />,
|
||||
);
|
||||
expect(
|
||||
containerError
|
||||
.querySelector('.line')
|
||||
?.classList.contains('severity-error-0'),
|
||||
).toBe(true);
|
||||
expect(screen.getByTestId('log-state-indicator-line')).toHaveClass(
|
||||
'severity-error-0',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,8 +138,11 @@ function LogStateIndicator({
|
||||
const severityClass = getSeverityClass(severityText, severityNumber);
|
||||
|
||||
return (
|
||||
<div className="log-state-indicator">
|
||||
<div className={cx('line', fontSize, severityClass)} />
|
||||
<div className="log-state-indicator" data-testid="log-state-indicator">
|
||||
<div
|
||||
className={cx('line', fontSize, severityClass)}
|
||||
data-testid="log-state-indicator-line"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -128,7 +128,9 @@ function OptionsMenu({
|
||||
>
|
||||
<span className="menu-row">
|
||||
{size}
|
||||
{fontSizeValue === size && <Check size={14} />}
|
||||
{fontSizeValue === size && (
|
||||
<Check size={14} data-testid="font-size-option-check" />
|
||||
)}
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
@@ -156,7 +158,7 @@ function OptionsMenu({
|
||||
</Button>
|
||||
</div>
|
||||
<div className="horizontal-line" />
|
||||
<div className="menu-container">
|
||||
<div className="menu-container" data-testid="format-options-menu">
|
||||
<div className="title">FORMAT</div>
|
||||
|
||||
<div className="menu-items">
|
||||
@@ -170,7 +172,9 @@ function OptionsMenu({
|
||||
<div className={cx('item-label')}>
|
||||
{item.label}
|
||||
|
||||
{selectedItem === item.key && <Check size={12} />}
|
||||
{selectedItem === item.key && (
|
||||
<Check size={12} data-testid="format-check-icon" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
|
||||
@@ -34,13 +35,14 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
mockUpdateFormatting.mockClear();
|
||||
});
|
||||
|
||||
function setup(): {
|
||||
async function setup(): Promise<{
|
||||
user: ReturnType<typeof userEvent.setup>;
|
||||
getByTestId: ReturnType<typeof render>['getByTestId'];
|
||||
findItemByLabel: (label: string) => Element | undefined;
|
||||
formatOnChange: jest.Mock<any, any>;
|
||||
maxLinesOnChange: jest.Mock<any, any>;
|
||||
fontSizeOnChange: jest.Mock<any, any>;
|
||||
} {
|
||||
}> {
|
||||
const user = userEvent.setup();
|
||||
const items = [
|
||||
{ key: 'raw', label: 'Raw', data: { title: 'max lines per row' } },
|
||||
{ key: 'list', label: 'Default' },
|
||||
@@ -76,16 +78,11 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Open the popover menu by default for each test
|
||||
const formatButton = getByTestId('periscope-btn-format-options');
|
||||
fireEvent.click(formatButton);
|
||||
|
||||
const getMenuItems = (): Element[] =>
|
||||
Array.from(document.querySelectorAll('.menu-items .item'));
|
||||
const findItemByLabel = (label: string): Element | undefined =>
|
||||
getMenuItems().find((el) => (el.textContent || '').includes(label));
|
||||
await user.click(formatButton);
|
||||
|
||||
return {
|
||||
user,
|
||||
getByTestId,
|
||||
findItemByLabel,
|
||||
formatOnChange,
|
||||
maxLinesOnChange,
|
||||
fontSizeOnChange,
|
||||
@@ -94,31 +91,36 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
|
||||
// Covers: opens menu, changes format selection, updates max-lines, changes font size
|
||||
it('opens and toggles format selection', async () => {
|
||||
const { findItemByLabel, formatOnChange } = setup();
|
||||
const { user, formatOnChange } = await setup();
|
||||
|
||||
// Assert initial selection
|
||||
const columnItem = findItemByLabel('Column') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(columnItem.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-table')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Change selection to 'Raw'
|
||||
const rawItem = findItemByLabel('Raw') as Element;
|
||||
fireEvent.click(rawItem as HTMLElement);
|
||||
await user.click(screen.getByTestId('format-option-raw'));
|
||||
await waitFor(() => {
|
||||
const rawEl = findItemByLabel('Raw') as Element;
|
||||
expect(document.querySelectorAll('.menu-items .item svg')).toHaveLength(1);
|
||||
expect(rawEl.querySelector('svg')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('format-check-icon')).toHaveLength(1);
|
||||
expect(
|
||||
within(screen.getByTestId('format-option-raw')).getByTestId(
|
||||
'format-check-icon',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(formatOnChange).toHaveBeenCalledWith('raw');
|
||||
});
|
||||
|
||||
it('increments max-lines and calls onChange', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
|
||||
// Increment max lines
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const initial = Number(input.value);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
await user.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Number(input.value)).toBe(initial + 1);
|
||||
@@ -129,9 +131,8 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('clamps a typed max-lines value to 10', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const { user, maxLinesOnChange, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '15');
|
||||
@@ -142,10 +143,9 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('stops max-lines at 10', async () => {
|
||||
const { getByTestId } = setup();
|
||||
const { user, getByTestId } = await setup();
|
||||
const input = getByTestId('max-lines-per-row-field') as HTMLInputElement;
|
||||
const increment = screen.getByRole('button', { name: 'More lines per row' });
|
||||
const user = userEvent.setup();
|
||||
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await user.click(increment);
|
||||
@@ -155,19 +155,23 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('changes font size to MEDIUM and calls onChange', async () => {
|
||||
const { fontSizeOnChange, getByTestId } = setup();
|
||||
const { user, fontSizeOnChange, getByTestId } = await setup();
|
||||
// Open font dropdown
|
||||
fireEvent.click(getByTestId('font-size-select'));
|
||||
await user.click(getByTestId('font-size-select'));
|
||||
|
||||
// Choose MEDIUM
|
||||
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
await user.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.MEDIUM}`)).getByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
|
||||
within(getByTestId(`font-size-option-${FontSize.SMALL}`)).queryByTestId(
|
||||
'font-size-option-check',
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() => {
|
||||
@@ -212,16 +216,16 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
renderWithOnOpen(undefined, 'table');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render "Edit columns" row when format is not table', () => {
|
||||
renderWithOnOpen(jest.fn(), 'raw');
|
||||
|
||||
expect(
|
||||
document.querySelector('[data-testid="periscope-btn-edit-columns"]'),
|
||||
).toBeNull();
|
||||
screen.queryByTestId('periscope-btn-edit-columns'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fires onOpenColumns and closes the popover when "Edit columns" is clicked', async () => {
|
||||
@@ -233,7 +237,7 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
expect(onOpenColumns).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => {
|
||||
// Popover content unmounts on close.
|
||||
expect(document.querySelector('.menu-container')).toBeNull();
|
||||
expect(screen.queryByTestId('format-option-table')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,8 +74,7 @@ function Harness({
|
||||
}
|
||||
|
||||
const getView = (): EditorView => {
|
||||
const dom = document.querySelector('.cm-editor');
|
||||
const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null;
|
||||
const view = EditorView.findFromDOM(screen.getByTestId('markdown-editor'));
|
||||
if (!view) {
|
||||
throw new Error('editor view not mounted');
|
||||
}
|
||||
@@ -151,11 +150,9 @@ describe('MarkdownEditor', () => {
|
||||
render(<Harness initialValue={'## Runbook\nowner {{team}}'} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.cm-md-heading')).toBeInTheDocument();
|
||||
expect(screen.getByText('## Runbook')).toHaveClass('cm-md-heading');
|
||||
});
|
||||
expect(document.querySelector('.cm-md-variable')).toHaveTextContent(
|
||||
'{{team}}',
|
||||
);
|
||||
expect(screen.getByText('{{team}}')).toHaveClass('cm-md-variable');
|
||||
});
|
||||
|
||||
describe('uncontrolled document', () => {
|
||||
|
||||
@@ -189,7 +189,13 @@ function MembersTable({
|
||||
<span className="members-pagination-range">
|
||||
{range[0]} — {range[1]}
|
||||
</span>
|
||||
<span className="members-pagination-total"> of {_total}</span>
|
||||
<span
|
||||
className="members-pagination-total"
|
||||
data-testid="members-pagination-total"
|
||||
>
|
||||
{' '}
|
||||
of {_total}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('MembersTable', () => {
|
||||
const onRowClick = jest.fn() as jest.MockedFunction<
|
||||
(member: MemberRow) => void
|
||||
>;
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<MembersTable
|
||||
@@ -88,7 +88,7 @@ describe('MembersTable', () => {
|
||||
|
||||
it('renders DELETED badge and calls onRowClick when a deleted member row is clicked', async () => {
|
||||
const onRowClick = jest.fn();
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const deletedMember: MemberRow = {
|
||||
id: 'user-del',
|
||||
name: 'Dave Deleted',
|
||||
@@ -129,7 +129,7 @@ describe('MembersTable', () => {
|
||||
});
|
||||
|
||||
it('hides pagination when total does not exceed pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -139,12 +139,12 @@ describe('MembersTable', () => {
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
screen.queryByTestId('members-pagination-total'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows pagination when total exceeds pageSize', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<MembersTable
|
||||
{...defaultProps}
|
||||
data={mockActiveMembers}
|
||||
@@ -153,11 +153,8 @@ describe('MembersTable', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
container.querySelector('.members-table-pagination'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.members-pagination-total'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('members-pagination-total')).toHaveTextContent(
|
||||
'of 25',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import MessageTip from './index';
|
||||
|
||||
@@ -35,13 +35,13 @@ describe('MessageTip', () => {
|
||||
// taken from antd docs
|
||||
// https://github.com/ant-design/ant-design/blob/master/components/alert/__tests__/index.test.tsx
|
||||
it('custom action', () => {
|
||||
const { container } = render(
|
||||
const { asFragment } = render(
|
||||
<MessageTip
|
||||
show
|
||||
message="Success Tips"
|
||||
action={<button type="button">Close</button>}
|
||||
/>,
|
||||
);
|
||||
expect(container.firstChild).toMatchSnapshot();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
|
||||
|
||||
exports[`MessageTip custom action 1`] = `
|
||||
.c0 {
|
||||
<DocumentFragment>
|
||||
.c0 {
|
||||
-webkit-align-items: center;
|
||||
-webkit-box-align: center;
|
||||
-ms-flex-align: center;
|
||||
@@ -9,46 +10,47 @@ exports[`MessageTip custom action 1`] = `
|
||||
}
|
||||
|
||||
<div
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
class="ant-alert ant-alert-info ant-alert-with-description c0 css-dev-only-do-not-override-2i2tap"
|
||||
data-show="true"
|
||||
role="alert"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
<span
|
||||
aria-label="info-circle"
|
||||
class="anticon anticon-info-circle ant-alert-icon"
|
||||
role="img"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-content"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
data-icon="info-circle"
|
||||
fill="currentColor"
|
||||
focusable="false"
|
||||
height="1em"
|
||||
viewBox="64 64 896 896"
|
||||
width="1em"
|
||||
>
|
||||
<path
|
||||
d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm32 664c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V456c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272zm-32-344a48.01 48.01 0 010-96 48.01 48.01 0 010 96z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
class="ant-alert-content"
|
||||
>
|
||||
Success Tips
|
||||
<div
|
||||
class="ant-alert-description"
|
||||
>
|
||||
Success Tips
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ant-alert-action"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
@@ -632,7 +632,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -746,6 +750,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onKeyDown={(e): void => {
|
||||
if ((e.key === 'Enter' || e.key === SPACEKEY) && isActive) {
|
||||
e.stopPropagation();
|
||||
@@ -777,7 +782,9 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{(option.type === 'custom' || option.type === 'regex') && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
{option.value && ensureValidOption(option.value) && (
|
||||
<Button
|
||||
@@ -1562,6 +1569,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-multiselect-dropdown"
|
||||
data-testid="custom-multiselect-dropdown"
|
||||
onMouseDown={handleDropdownMouseDown}
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
@@ -1583,6 +1591,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
active: activeIndex === 0,
|
||||
})}
|
||||
key={`all-option-${allOptionsSelected}`}
|
||||
data-testid="all-option"
|
||||
id="option-0"
|
||||
onMouseEnter={(): void => {
|
||||
setActiveIndex(0);
|
||||
@@ -1641,7 +1650,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divider" />
|
||||
<div className="divider" data-testid="all-option-divider" />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1711,7 +1720,11 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
)}
|
||||
|
||||
{/* Navigation help footer */}
|
||||
<div className="navigation-footer" role="note">
|
||||
<div
|
||||
className="navigation-footer"
|
||||
role="note"
|
||||
data-testid="navigation-footer"
|
||||
>
|
||||
{!loading &&
|
||||
!errorMessage &&
|
||||
!noDataMessage &&
|
||||
@@ -1726,7 +1739,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1734,7 +1747,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -1744,7 +1757,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && !waitingMessage && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
@@ -1959,6 +1972,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
|
||||
'ant-select-selection-item-active': isActive,
|
||||
'ant-select-selection-item-selected': isSelected,
|
||||
})}
|
||||
data-testid={`selected-tag-${value}`}
|
||||
style={
|
||||
isActive || isSelected
|
||||
? {
|
||||
|
||||
@@ -170,7 +170,11 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
const uniqueKey = `${text.substring(0, 3)}-${part.substring(0, 3)}-${i}`;
|
||||
|
||||
return part.toLowerCase() === searchQuery.toLowerCase() ? (
|
||||
<span key={uniqueKey} className="highlight-text">
|
||||
<span
|
||||
key={uniqueKey}
|
||||
className="highlight-text"
|
||||
data-testid="highlight-text"
|
||||
>
|
||||
{part}
|
||||
</span>
|
||||
) : (
|
||||
@@ -220,6 +224,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
selected: isSelected,
|
||||
active: isActive,
|
||||
})}
|
||||
data-testid={`option-item-${option.value}`}
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
handleSelection();
|
||||
@@ -241,7 +246,9 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
{highlightMatchedText(String(option.label || ''), searchText)}
|
||||
</span>
|
||||
{option.type === 'custom' && (
|
||||
<div className="option-badge">{capitalize(option.type)}</div>
|
||||
<div className="option-badge" data-testid="option-badge">
|
||||
{capitalize(option.type)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -268,6 +275,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
() => (
|
||||
<X
|
||||
size="md"
|
||||
data-testid="custom-select-clear"
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
if (onChange) {
|
||||
@@ -528,6 +536,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="custom-select-dropdown"
|
||||
data-testid="custom-select-dropdown"
|
||||
onClick={handleDropdownClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
onScroll={handleDropdownScroll}
|
||||
@@ -587,7 +596,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</section>
|
||||
)}
|
||||
{loading && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -595,7 +604,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{!loading && waitingMessage && (
|
||||
<div className="navigation-loading">
|
||||
<div className="navigation-loading" data-testid="navigation-loading">
|
||||
<div className="navigation-icons">
|
||||
<Loader size="md" className="animate-spin" />
|
||||
</div>
|
||||
@@ -605,7 +614,7 @@ const CustomSelect: React.FC<CustomSelectProps> = ({
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && !loading && (
|
||||
<div className="navigation-error">
|
||||
<div className="navigation-error" data-testid="navigation-error">
|
||||
<div className="navigation-text">
|
||||
{errorMessage || SOMETHING_WENT_WRONG}
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
import type { CustomMultiSelectProps } from '../types';
|
||||
|
||||
// Mock scrollIntoView which isn't available in JSDOM
|
||||
window.HTMLElement.prototype.scrollIntoView = jest.fn();
|
||||
@@ -49,6 +50,26 @@ const mockGroupedOptions = [
|
||||
},
|
||||
];
|
||||
|
||||
function StatefulMultiSelect({
|
||||
initialValue,
|
||||
onChange,
|
||||
}: {
|
||||
initialValue: string[];
|
||||
onChange: CustomMultiSelectProps['onChange'];
|
||||
}): JSX.Element {
|
||||
const [value, setValue] = useState<string[] | string>(initialValue);
|
||||
return (
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
value={value}
|
||||
onChange={(next, option): void => {
|
||||
onChange?.(next, option);
|
||||
setValue(next);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
let user: ReturnType<typeof userEvent.setup>;
|
||||
let mockOnChange: jest.Mock;
|
||||
@@ -114,16 +135,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Verify the component renders without crashing
|
||||
expect(combobox).toBeInTheDocument();
|
||||
@@ -141,30 +154,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -188,49 +191,31 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should filter to show only Frontend and Backend with highlighted "end"
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "end" text in the options
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
|
||||
// Check that Frontend and Backend options are present with highlighted text
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Front') &&
|
||||
label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
const hasBackendOption = Array.from(optionLabels).some(
|
||||
(label) =>
|
||||
label.textContent?.includes('Back') && label.textContent?.includes('end'),
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveTextContent(
|
||||
'Backend',
|
||||
);
|
||||
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
expect(hasBackendOption).toBe(true);
|
||||
|
||||
// Other options should be filtered out
|
||||
const hasDatabaseOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Database'),
|
||||
);
|
||||
const hasApiGatewayOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('API Gateway'),
|
||||
);
|
||||
|
||||
expect(hasDatabaseOption).toBe(false);
|
||||
expect(hasApiGatewayOption).toBe(false);
|
||||
expect(
|
||||
screen.queryByTestId('option-item-database'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('option-item-api-gateway'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,15 +231,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Type comma-separated values
|
||||
await user.type(searchInput, 'test1, test2, test3');
|
||||
}
|
||||
// Type comma-separated values
|
||||
await user.type(combobox, 'test1, test2, test3');
|
||||
|
||||
// Press Enter to create the comma-separated chips
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -294,14 +272,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-multiselect-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-label-text') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top (after ALL option if present)
|
||||
expect(optionTexts[0]).toBe('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toBe(screen.getByTestId('option-item-database'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -319,30 +296,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front' and highlight search term
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionLabels = document.querySelectorAll('.option-label-text');
|
||||
const hasFrontendOption = Array.from(optionLabels).some((label) =>
|
||||
label.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -362,21 +329,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -393,14 +352,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -411,13 +363,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -445,23 +395,19 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('option-item-frontend');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
// The active option should be an option in the dropdown
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option (goes back to ALL)
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
const activeOption = screen.getByTestId('all-option');
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption).toHaveAttribute('role', 'option');
|
||||
expect(activeOption?.textContent).toContain('ALL');
|
||||
expect(activeOption).toHaveTextContent('ALL');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -499,19 +445,14 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption).toHaveClass('active');
|
||||
expect(activeOption?.textContent).toBeTruthy();
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Tab again to move to next option
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -558,10 +499,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Delete the active chip
|
||||
@@ -575,11 +515,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify that the active chip (backend) is highlighted for deletion
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
expect(activeChip).toHaveTextContent('backend');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -688,9 +626,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByRole('checkbox'));
|
||||
|
||||
@@ -726,9 +662,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('combobox'));
|
||||
const backendRow = (await screen.findByText('Backend')).closest(
|
||||
'[role="option"]',
|
||||
) as HTMLElement;
|
||||
const backendRow = await screen.findByTestId('option-item-backend');
|
||||
mockOnChange.mockClear();
|
||||
await user.click(within(backendRow).getByText('Toggle'));
|
||||
|
||||
@@ -751,8 +685,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Database')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Gateway')).toBeInTheDocument();
|
||||
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
expect(screen.getByText('Refreshing values...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -770,8 +703,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -813,21 +745,17 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// All chips should be selected (have selected class)
|
||||
const selectedChips = document.querySelectorAll(
|
||||
'.ant-select-selection-item-selected',
|
||||
);
|
||||
const selectedChips = screen
|
||||
.getAllByTestId(/^selected-tag-/)
|
||||
.filter((chip) =>
|
||||
chip.classList.contains('ant-select-selection-item-selected'),
|
||||
);
|
||||
expect(selectedChips.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify that all expected chips are present AND selected
|
||||
const frontendChip = screen
|
||||
.getByText('frontend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const backendChip = screen
|
||||
.getByText('backend')
|
||||
.closest('.ant-select-selection-item');
|
||||
const databaseChip = screen
|
||||
.getByText('database')
|
||||
.closest('.ant-select-selection-item');
|
||||
const frontendChip = screen.getByTestId('selected-tag-frontend');
|
||||
const backendChip = screen.getByTestId('selected-tag-backend');
|
||||
const databaseChip = screen.getByTestId('selected-tag-database');
|
||||
|
||||
expect(frontendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
expect(backendChip).toHaveClass('ant-select-selection-item-selected');
|
||||
@@ -850,11 +778,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
if (clearButton) {
|
||||
await user.click(clearButton as Element);
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
}
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
expect(mockOnChange).toHaveBeenCalledWith([], []);
|
||||
});
|
||||
|
||||
it('CA-03: Individual chip removal', async () => {
|
||||
@@ -867,12 +792,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
);
|
||||
|
||||
// Find and click the close button on a chip
|
||||
const removeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
const removeButtons = screen.getAllByLabelText(/^Remove tag /);
|
||||
expect(removeButtons).toHaveLength(2);
|
||||
|
||||
await user.click(removeButtons[1] as Element);
|
||||
await user.click(removeButtons[1]);
|
||||
|
||||
// Should call onChange with one item removed
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -911,9 +834,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Dropdown should be hidden (not completely removed from DOM)
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(dropdown).toHaveStyle('pointer-events: none');
|
||||
expect(
|
||||
screen.getByTestId('custom-multiselect-dropdown'),
|
||||
).toBeInTheDocument();
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -951,14 +875,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-input');
|
||||
}
|
||||
await user.type(combobox, 'custom-input');
|
||||
|
||||
// Press Enter in input field
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -984,18 +901,11 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'search-text');
|
||||
}
|
||||
await user.type(combobox, 'search-text');
|
||||
|
||||
// Verify search text is in input
|
||||
await waitFor(() => {
|
||||
expect(searchInput).toHaveValue('search-text');
|
||||
expect(combobox).toHaveValue('search-text');
|
||||
});
|
||||
|
||||
// Press Escape to close dropdown
|
||||
@@ -1003,9 +913,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close and search text should be cleared
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(searchInput).toHaveValue('');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
expect(combobox).toHaveValue('');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1029,8 +938,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(allOption).toBeInTheDocument();
|
||||
|
||||
// Check for divider after ALL option
|
||||
const divider = document.querySelector('.divider');
|
||||
expect(divider).toBeInTheDocument();
|
||||
expect(screen.getByTestId('all-option-divider')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1086,8 +994,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
// Should show navigation footer
|
||||
const footer = document.querySelector('.navigation-footer');
|
||||
expect(footer).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-footer')).toBeInTheDocument();
|
||||
|
||||
// Should show navigation hint
|
||||
expect(screen.getByText('to navigate')).toBeInTheDocument();
|
||||
@@ -1161,10 +1068,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
describe('Advanced Keyboard Navigation (AKN)', () => {
|
||||
it('AKN-01: Shift + Arrow + Del chip deletion', async () => {
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
options={mockOptions}
|
||||
<StatefulMultiSelect
|
||||
initialValue={['frontend', 'backend', 'database']}
|
||||
onChange={mockOnChange}
|
||||
value={['frontend', 'backend', 'database']}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -1176,12 +1082,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should have an active chip - verify initial chip
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we're on the last chip (database)
|
||||
expect(activeChip?.textContent).toContain('database');
|
||||
expect(screen.getByTestId('selected-tag-database')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Shift + Arrow to navigate to previous chip
|
||||
@@ -1189,12 +1093,10 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Verify we're on a different chip (backend)
|
||||
await waitFor(() => {
|
||||
const activeChip = document.querySelector(
|
||||
'.ant-select-selection-item-active',
|
||||
);
|
||||
expect(activeChip).toBeInTheDocument();
|
||||
// Verify we moved to the previous chip (backend)
|
||||
expect(activeChip?.textContent).toContain('backend');
|
||||
expect(screen.getByTestId('selected-tag-backend')).toHaveClass(
|
||||
'ant-select-selection-item-active',
|
||||
);
|
||||
});
|
||||
|
||||
// Use Del to delete the active chip
|
||||
@@ -1203,8 +1105,9 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
// Verify the chip was deleted
|
||||
await waitFor(() => {
|
||||
// Check that the backend chip is no longer present
|
||||
const backendChip = document.querySelector('.ant-select-selection-item');
|
||||
expect(backendChip?.textContent).not.toContain('backend');
|
||||
expect(
|
||||
screen.queryByTestId('selected-tag-backend'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Verify onChange was called with the updated value (without backend)
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -1235,9 +1138,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close - check for hidden state
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
// The dropdown should be hidden with the hidden class
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1256,32 +1158,20 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const labelElement = item.querySelector('.option-label-text');
|
||||
return labelElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text should contain "front"
|
||||
@@ -1325,12 +1215,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should create custom value)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -1364,11 +1249,8 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByLabelText('close-circle'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith([], []);
|
||||
@@ -1426,19 +1308,13 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(50); // Reduced length to avoid timeout
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -1469,25 +1345,16 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1570,8 +1437,7 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Escape}');
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,9 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -29,9 +30,6 @@ const mockOptions = [
|
||||
{ label: 'Option 3', value: 'option3' },
|
||||
];
|
||||
|
||||
// CSS selector for retry button
|
||||
const RETRY_BUTTON_SELECTOR = '[data-testid="retry-button"]';
|
||||
|
||||
describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
@@ -61,8 +59,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Check that retry button (ReloadOutlined icon) is present
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
expect(screen.getByTestId('retry-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button when 4xx error occurs and error message is displayed (current behavior)', async () => {
|
||||
@@ -88,11 +85,11 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
expect(screen.getByText(errorMessage)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('retry-button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should call onRetry function when retry button is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const mockOnRetry = jest.fn();
|
||||
const errorMessage = 'Internal Server Error (500)';
|
||||
|
||||
@@ -108,7 +105,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Wait for dropdown to appear
|
||||
await waitFor(() => {
|
||||
@@ -116,10 +113,7 @@ describe('CustomMultiSelect - Retry Functionality', () => {
|
||||
});
|
||||
|
||||
// Find and click the retry button
|
||||
const retryButton = document.querySelector(RETRY_BUTTON_SELECTOR);
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryButton as Element);
|
||||
await user.click(screen.getByTestId('retry-button'));
|
||||
|
||||
// Verify onRetry was called
|
||||
expect(mockOnRetry).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -4,9 +4,10 @@ import {
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomMultiSelect from '../CustomMultiSelect';
|
||||
|
||||
@@ -156,6 +157,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('removes a tag when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const handleChange = jest.fn();
|
||||
renderWithVirtuoso(
|
||||
<CustomMultiSelect
|
||||
@@ -166,10 +168,7 @@ describe('CustomMultiSelect Component', () => {
|
||||
);
|
||||
|
||||
// Find close button on Option 1 tag and click it
|
||||
const closeButtons = document.querySelectorAll(
|
||||
'.ant-select-selection-item-remove',
|
||||
);
|
||||
fireEvent.click(closeButtons[0]);
|
||||
await user.click(screen.getByLabelText('Remove tag option1'));
|
||||
|
||||
// Verify onChange was called with remaining option
|
||||
expect(handleChange).toHaveBeenCalledWith(
|
||||
@@ -179,39 +178,24 @@ describe('CustomMultiSelect Component', () => {
|
||||
});
|
||||
|
||||
it('filters options when searching', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithVirtuoso(<CustomMultiSelect options={mockOptions} />);
|
||||
|
||||
// Open dropdown
|
||||
const selectElement = screen.getByRole('combobox');
|
||||
fireEvent.mouseDown(selectElement);
|
||||
await user.click(selectElement);
|
||||
|
||||
// Type into search box - get input directly
|
||||
const inputElement = selectElement.querySelector('input');
|
||||
if (inputElement) {
|
||||
fireEvent.change(inputElement, { target: { value: '2' } });
|
||||
}
|
||||
// Type into search box - the combobox is the search input
|
||||
await user.type(selectElement, '2');
|
||||
|
||||
// Wait for the dropdown filtering to happen
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector(
|
||||
'.custom-multiselect-dropdown',
|
||||
);
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Verify Option 2 is visible in the dropdown
|
||||
const options = document.querySelectorAll('.option-label-text');
|
||||
let foundOption2 = false;
|
||||
|
||||
options.forEach((option) => {
|
||||
const text = option.textContent || '';
|
||||
if (text.includes('Option 2')) {
|
||||
foundOption2 = true;
|
||||
}
|
||||
});
|
||||
|
||||
expect(foundOption2).toBe(true);
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('option-item-option1')).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(
|
||||
within(screen.getByTestId('custom-multiselect-dropdown'))
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((option) => option.dataset.testid),
|
||||
).toStrictEqual(['option-item-2', 'option-item-option2']);
|
||||
});
|
||||
|
||||
it('renders grouped options correctly', async () => {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -67,34 +66,19 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find input by class name
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type partial match that doesn't exist exactly
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'fro');
|
||||
}
|
||||
await user.type(combobox, 'fro');
|
||||
|
||||
// Check that custom value appears in dropdown with custom tag
|
||||
await waitFor(() => {
|
||||
// Find the custom option with "fro" text and "Custom" badge
|
||||
const customOptions = screen.getAllByText('fro');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-fro');
|
||||
expect(customOption).toHaveTextContent('fro');
|
||||
|
||||
// Verify it has the custom badge
|
||||
const optionItem = customOption?.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
expect(badge).toBeInTheDocument();
|
||||
expect(badge?.textContent).toBe('Custom');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the custom value
|
||||
@@ -120,30 +104,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'frontend');
|
||||
}
|
||||
await user.type(combobox, 'frontend');
|
||||
|
||||
// Should show the Frontend option in dropdown for exact match
|
||||
await waitFor(() => {
|
||||
// Check for highlighted "frontend" text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Frontend');
|
||||
|
||||
// Frontend option should be visible in dropdown - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
});
|
||||
|
||||
// Press Enter to select the exact match
|
||||
@@ -174,14 +148,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
|
||||
const options = dropdown?.querySelectorAll('.option-content') || [];
|
||||
const optionTexts = Array.from(options).map((el) => el.textContent);
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
|
||||
// Database should be at the top
|
||||
expect(optionTexts[0]).toContain('Database');
|
||||
const [firstOption] = screen.getAllByTestId(/^option-item-/);
|
||||
expect(firstOption).toHaveTextContent('Database');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -197,30 +168,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Find and type in search input
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should filter to show only options containing 'front'
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text within the Frontend option
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('Front');
|
||||
|
||||
// Should show Frontend option (highlighted) - use a simpler approach
|
||||
const optionContents = document.querySelectorAll('.option-content');
|
||||
const hasFrontendOption = Array.from(optionContents).some((content) =>
|
||||
content.textContent?.includes('Frontend'),
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveTextContent(
|
||||
'Frontend',
|
||||
);
|
||||
expect(hasFrontendOption).toBe(true);
|
||||
|
||||
// Backend and Database should not be visible
|
||||
expect(screen.queryByText('Backend')).not.toBeInTheDocument();
|
||||
@@ -238,21 +199,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'end');
|
||||
}
|
||||
await user.type(combobox, 'end');
|
||||
|
||||
// Should highlight matching text in options
|
||||
await waitFor(() => {
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('end');
|
||||
});
|
||||
});
|
||||
@@ -267,14 +220,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
}
|
||||
await user.type(combobox, 'nonexistent');
|
||||
|
||||
// Should show custom value option when no matches found
|
||||
await waitFor(() => {
|
||||
@@ -285,13 +231,11 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.queryByText('API Gateway')).not.toBeInTheDocument();
|
||||
|
||||
// Should show custom value option
|
||||
const customOptions = screen.getAllByText('nonexistent');
|
||||
const customOption = customOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(customOption).toBeInTheDocument();
|
||||
const customOption = screen.getByTestId('option-item-nonexistent');
|
||||
expect(customOption).toHaveTextContent('nonexistent');
|
||||
expect(within(customOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -313,19 +257,15 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// First option should be active
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
// Verify it's the first option (Frontend)
|
||||
expect(activeOption?.textContent).toContain('Backend');
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
|
||||
// Arrow up should go to previous option
|
||||
await user.keyboard('{ArrowUp}');
|
||||
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(activeOption?.textContent).toContain('Frontend');
|
||||
expect(screen.getByTestId('option-item-frontend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -410,8 +350,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.keyboard('{Tab}');
|
||||
|
||||
// Should still be within dropdown context
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -453,8 +392,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const loadingFooter = document.querySelector('.navigation-loading');
|
||||
expect(loadingFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-loading')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -471,8 +409,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
await user.click(combobox);
|
||||
|
||||
await waitFor(() => {
|
||||
const errorFooter = document.querySelector('.navigation-error');
|
||||
expect(errorFooter).toBeInTheDocument();
|
||||
expect(screen.getByTestId('navigation-error')).toBeInTheDocument();
|
||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -605,8 +542,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.custom-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
expect(screen.getByTestId('custom-select-dropdown')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Focus should remain manageable
|
||||
@@ -679,8 +615,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -714,8 +649,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Should navigate to first option in dropdown
|
||||
await waitFor(() => {
|
||||
const activeOption = document.querySelector('.option-item.active');
|
||||
expect(activeOption).toBeInTheDocument();
|
||||
expect(screen.getByTestId('option-item-backend')).toHaveClass('active');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -732,32 +666,20 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'front');
|
||||
}
|
||||
await user.type(combobox, 'front');
|
||||
|
||||
// Should show highlighted options with correct order
|
||||
await waitFor(() => {
|
||||
// Check for highlighted text
|
||||
const highlightedElements = document.querySelectorAll('.highlight-text');
|
||||
const highlightTexts = Array.from(highlightedElements).map(
|
||||
(el) => el.textContent,
|
||||
);
|
||||
const highlightTexts = screen
|
||||
.getAllByTestId('highlight-text')
|
||||
.map((el) => el.textContent);
|
||||
expect(highlightTexts).toContain('front');
|
||||
|
||||
// Get all option items to check the order
|
||||
const optionItems = document.querySelectorAll('.option-item');
|
||||
const optionTexts = Array.from(optionItems)
|
||||
.map((item) => {
|
||||
const contentElement = item.querySelector('.option-content');
|
||||
return contentElement?.textContent?.trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
const optionTexts = screen
|
||||
.getAllByTestId(/^option-item-/)
|
||||
.map((item) => item.textContent?.trim());
|
||||
|
||||
// Custom value "front" should appear first (above Frontend)
|
||||
// The text includes "Custom" badge, so check for "front" in the text
|
||||
@@ -807,12 +729,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
});
|
||||
|
||||
// Now type something and press Enter to save
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'custom-value');
|
||||
}
|
||||
await user.type(combobox, 'custom-value');
|
||||
|
||||
// Press Enter to save (should close dropdown)
|
||||
await user.keyboard('{Enter}');
|
||||
@@ -847,11 +764,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should call onChange immediately (no loading state in this component)
|
||||
expect(mockOnChangeWithDelay).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -870,11 +784,8 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const clearButton = document.querySelector('.ant-select-clear');
|
||||
expect(clearButton).toBeInTheDocument();
|
||||
|
||||
// Click clear button
|
||||
await user.click(clearButton as Element);
|
||||
await user.click(screen.getByTestId('custom-select-clear'));
|
||||
|
||||
// Should clear the single selection
|
||||
expect(mockOnChange).toHaveBeenCalledWith(undefined, undefined);
|
||||
@@ -927,19 +838,13 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
const combobox = screen.getByRole('combobox');
|
||||
await user.click(combobox);
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
// Type a long search value
|
||||
if (searchInput) {
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(searchInput, longSearchValue);
|
||||
}
|
||||
const longSearchValue = 'a'.repeat(100);
|
||||
await user.type(combobox, longSearchValue);
|
||||
|
||||
// Should not overflow or break layout
|
||||
await waitFor(() => {
|
||||
// oxlint-disable-next-line signoz/no-dom-node-access -- antd's search wrapper has no test hook; the test reads its computed overflow
|
||||
const searchContainer = document.querySelector(
|
||||
'.ant-select-selection-search',
|
||||
);
|
||||
@@ -962,12 +867,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(combobox).toHaveFocus();
|
||||
|
||||
// Should be able to type even with loading state
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
if (searchInput) {
|
||||
await user.type(searchInput, 'test');
|
||||
}
|
||||
await user.type(combobox, 'test');
|
||||
|
||||
// Should not be blocked by loading spinner
|
||||
expect(combobox).not.toBeDisabled();
|
||||
@@ -986,25 +886,16 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
expect(screen.getByText('Frontend')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector(
|
||||
'.ant-select-selection-search-input',
|
||||
);
|
||||
expect(searchInput).toBeInTheDocument();
|
||||
|
||||
if (searchInput) {
|
||||
// Test regex pattern
|
||||
await user.type(searchInput, '.*test.*');
|
||||
}
|
||||
// Test regex pattern
|
||||
await user.type(combobox, '.*test.*');
|
||||
|
||||
// Should create custom value for regex pattern
|
||||
await waitFor(() => {
|
||||
const regexOptions = screen.getAllByText('.*test.*');
|
||||
const regexOption = regexOptions.find((option) => {
|
||||
const optionItem = option.closest('.option-item');
|
||||
const badge = optionItem?.querySelector('.option-badge');
|
||||
return badge?.textContent === 'Custom';
|
||||
});
|
||||
expect(regexOption).toBeInTheDocument();
|
||||
const regexOption = screen.getByTestId('option-item-.*test.*');
|
||||
expect(regexOption).toHaveTextContent('.*test.*');
|
||||
expect(within(regexOption).getByTestId('option-badge')).toHaveTextContent(
|
||||
'Custom',
|
||||
);
|
||||
});
|
||||
|
||||
// Press Enter to create the regex value
|
||||
@@ -1076,8 +967,7 @@ describe('CustomSelect - Comprehensive Tests', () => {
|
||||
|
||||
// Dropdown should close after selection in single select
|
||||
await waitFor(() => {
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toHaveClass('ant-select-dropdown-hidden');
|
||||
expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import CustomSelect from '../CustomSelect';
|
||||
|
||||
@@ -93,11 +99,12 @@ describe('CustomSelect Component', () => {
|
||||
// Dropdown should only show Option 2
|
||||
await waitFor(() => {
|
||||
// Check that the dropdown is present
|
||||
const dropdownElement = document.querySelector('.custom-select-dropdown');
|
||||
const dropdownElement = screen.getByTestId('custom-select-dropdown');
|
||||
expect(dropdownElement).toBeInTheDocument();
|
||||
|
||||
// Use a simple approach to verify filtering
|
||||
const allOptionsInDropdown = document.querySelectorAll('.option-item');
|
||||
const allOptionsInDropdown =
|
||||
within(dropdownElement).queryAllByTestId(/^option-item-/);
|
||||
let foundOption2 = false;
|
||||
|
||||
allOptionsInDropdown.forEach((option) => {
|
||||
|
||||
@@ -40,7 +40,7 @@ function ListViewOrderBy({
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [selectOptions, setSelectOptions] = useState<
|
||||
{ label: string; value: string }[]
|
||||
{ label: string; value: string; 'data-testid': string }[]
|
||||
>([]);
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
@@ -75,8 +75,16 @@ function ListViewOrderBy({
|
||||
|
||||
setSelectOptions(
|
||||
uniqueKeys.flatMap((key) => [
|
||||
{ label: `${key} (desc)`, value: `${key}:desc` },
|
||||
{ label: `${key} (asc)`, value: `${key}:asc` },
|
||||
{
|
||||
label: `${key} (desc)`,
|
||||
value: `${key}:desc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
{
|
||||
label: `${key} (asc)`,
|
||||
value: `${key}:asc`,
|
||||
'data-testid': 'list-view-order-by-option',
|
||||
},
|
||||
]),
|
||||
);
|
||||
}, [data, searchInput, extraKeysSignature]);
|
||||
|
||||
@@ -59,9 +59,9 @@ const openDropdown = (): void => {
|
||||
};
|
||||
|
||||
const getOptionLabels = (): string[] =>
|
||||
Array.from(document.querySelectorAll('.ant-select-item-option-content')).map(
|
||||
(node) => node.textContent ?? '',
|
||||
);
|
||||
screen
|
||||
.queryAllByTestId('list-view-order-by-option')
|
||||
.map((node) => node.textContent ?? '');
|
||||
|
||||
describe('ListViewOrderBy', () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { act, render, screen, userEvent, within } from 'tests/test-utils';
|
||||
|
||||
import OverflowInputToolTip from './OverflowInputToolTip';
|
||||
|
||||
const TOOLTIP_INNER_SELECTOR = '.ant-tooltip-inner';
|
||||
// Utility to mock overflow behaviour on inputs / elements.
|
||||
// Stubs HTMLElement.prototype.clientWidth, scrollWidth and offsetWidth used by component.
|
||||
function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
@@ -22,21 +21,17 @@ function mockOverflow(clientWidth: number, scrollWidth: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
function queryTooltipInner(): HTMLElement | null {
|
||||
// find element that has role="tooltip" (could be the inner itself)
|
||||
const tooltip = document.querySelector<HTMLElement>('[role="tooltip"]');
|
||||
if (!tooltip) {
|
||||
return document.querySelector(TOOLTIP_INNER_SELECTOR);
|
||||
}
|
||||
const ANTD_TOOLTIP_OPEN_DELAY_MS = 100;
|
||||
|
||||
// if the role element is already the inner, return it; otherwise return its descendant
|
||||
if (tooltip.classList.contains('ant-tooltip-inner')) {
|
||||
return tooltip;
|
||||
}
|
||||
return (
|
||||
(tooltip.querySelector(TOOLTIP_INNER_SELECTOR) as HTMLElement) ??
|
||||
document.querySelector(TOOLTIP_INNER_SELECTOR)
|
||||
);
|
||||
async function hoverPastOpenDelay(element: HTMLElement): Promise<void> {
|
||||
jest.useFakeTimers();
|
||||
const user = userEvent.setup({
|
||||
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
|
||||
});
|
||||
await user.hover(element);
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(ANTD_TOOLTIP_OPEN_DELAY_MS * 2);
|
||||
});
|
||||
}
|
||||
|
||||
describe('OverflowInputToolTip', () => {
|
||||
@@ -44,6 +39,10 @@ describe('OverflowInputToolTip', () => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('shows tooltip when content overflows and input is clamped at maxAutoWidth', async () => {
|
||||
mockOverflow(150, 250); // clientWidth >= maxAutoWidth (150), scrollWidth > clientWidth
|
||||
|
||||
@@ -51,16 +50,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).not.toBeNull();
|
||||
});
|
||||
|
||||
const tooltipInner = queryTooltipInner();
|
||||
if (!tooltipInner) {
|
||||
throw new Error('Tooltip inner not found');
|
||||
}
|
||||
const tooltip = await screen.findByRole('tooltip');
|
||||
expect(
|
||||
within(tooltipInner).getByText('Very long overflowing text'),
|
||||
within(tooltip).getByText('Very long overflowing text'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -69,11 +61,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Short text" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does NOT show tooltip when content overflows but input is NOT at maxAutoWidth', async () => {
|
||||
@@ -81,11 +71,9 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Long but input not clamped" />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uncontrolled input allows typing', async () => {
|
||||
@@ -102,24 +90,20 @@ describe('OverflowInputToolTip', () => {
|
||||
|
||||
render(<OverflowInputToolTip value="Overflowing!" disabled />);
|
||||
|
||||
await userEvent.hover(screen.getByRole('textbox'));
|
||||
await hoverPastOpenDelay(screen.getByRole('textbox'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryTooltipInner()).toBeNull();
|
||||
});
|
||||
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders mirror span and input correctly (structural assertions instead of snapshot)', () => {
|
||||
const { container } = render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = container.querySelector('.overflow-input-mirror');
|
||||
const input = container.querySelector('input') as HTMLInputElement | null;
|
||||
render(<OverflowInputToolTip value="Snapshot" />);
|
||||
const mirror = screen.getByTestId('overflow-input-mirror');
|
||||
const input = screen.getByRole('textbox');
|
||||
|
||||
expect(mirror).toBeTruthy();
|
||||
expect(mirror?.textContent).toBe('Snapshot');
|
||||
expect(input).toBeTruthy();
|
||||
expect(input?.value).toBe('Snapshot');
|
||||
expect(mirror.textContent).toBe('Snapshot');
|
||||
expect(input).toHaveValue('Snapshot');
|
||||
|
||||
// width should be set inline (component calculates width on mount)
|
||||
expect(input?.getAttribute('style')).toContain('width:');
|
||||
expect(input.getAttribute('style')).toContain('width:');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,7 +49,12 @@ function OverflowInputToolTip({
|
||||
|
||||
return (
|
||||
<>
|
||||
<span ref={mirrorRef} aria-hidden className="overflow-input-mirror" />
|
||||
<span
|
||||
ref={mirrorRef}
|
||||
aria-hidden
|
||||
className="overflow-input-mirror"
|
||||
data-testid="overflow-input-mirror"
|
||||
/>
|
||||
<Tooltip title={tooltipTitle} placement={tooltipPlacement}>
|
||||
<Input
|
||||
{...rest}
|
||||
|
||||
@@ -105,6 +105,8 @@ const stopEventsExtension = EditorView.domEventHandlers({
|
||||
},
|
||||
});
|
||||
|
||||
const EDITOR_BASIC_SETUP = { lineNumbers: false };
|
||||
|
||||
interface QuerySearchProps {
|
||||
placeholder?: string;
|
||||
onChange: (value: string) => void;
|
||||
@@ -317,23 +319,20 @@ function QuerySearch({
|
||||
500,
|
||||
);
|
||||
|
||||
const toggleSuggestions = useCallback(
|
||||
(timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (isFocused) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
const toggleSuggestions = useCallback((timeout?: number) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!editorRef.current) {
|
||||
return;
|
||||
}
|
||||
if (editorRef.current.hasFocus) {
|
||||
startCompletion(editorRef.current);
|
||||
} else {
|
||||
closeCompletion(editorRef.current);
|
||||
}
|
||||
}, timeout);
|
||||
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
},
|
||||
[isFocused],
|
||||
);
|
||||
return (): void => clearTimeout(timeoutId);
|
||||
}, []);
|
||||
|
||||
const fetchKeySuggestions = useCallback(
|
||||
async (searchText?: string): Promise<void> => {
|
||||
@@ -716,14 +715,17 @@ function QuerySearch({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleChange = (value: string): void => {
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
|
||||
const handleChange = useCallback((value: string): void => {
|
||||
if (isProgrammaticChangeRef.current) {
|
||||
isProgrammaticChangeRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
onChange(value);
|
||||
};
|
||||
onChangeRef.current(value);
|
||||
}, []);
|
||||
|
||||
const handleBlur = (): void => {
|
||||
const currentExpression = getCurrentExpression();
|
||||
@@ -1477,6 +1479,65 @@ 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);
|
||||
@@ -1597,7 +1658,10 @@ function QuerySearch({
|
||||
{showScopeChip && <ScopeChip expression={initialExpression ?? ''} />}
|
||||
{isScopedFilter && !showScopeChip ? (
|
||||
<Tooltip title={initialExpression || ''} placement="left">
|
||||
<div className="query-search-initial-scope-label">
|
||||
<div
|
||||
className="query-search-initial-scope-label"
|
||||
data-testid="query-search-initial-scope-label"
|
||||
>
|
||||
<Filter
|
||||
size={14}
|
||||
style={{
|
||||
@@ -1650,56 +1714,9 @@ function QuerySearch({
|
||||
hasErrors: validation.errors.length > 0,
|
||||
hasInitialExpression: isScopedFilter && !showScopeChip,
|
||||
})}
|
||||
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,
|
||||
},
|
||||
]),
|
||||
),
|
||||
]}
|
||||
extensions={editorExtensions}
|
||||
placeholder={placeholder}
|
||||
basicSetup={{
|
||||
lineNumbers: false,
|
||||
}}
|
||||
basicSetup={EDITOR_BASIC_SETUP}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
}}
|
||||
|
||||
@@ -168,6 +168,7 @@ export function renderRecentDeleteButton(
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'cm-recent-delete';
|
||||
btn.dataset.testid = 'query-search-recent-delete';
|
||||
btn.setAttribute('aria-label', 'Remove from recent searches');
|
||||
btn.title = 'Remove from recent searches';
|
||||
btn.textContent = '×';
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
@@ -19,6 +19,7 @@ import { EQueryType } from 'types/common/dashboard';
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
|
||||
const EDITOR_TEST_ID = 'query-aggregation-editor';
|
||||
// CodeMirror's suggestion popup is slow to open under a parallel jest run.
|
||||
@@ -116,7 +117,7 @@ async function enterAggregation(
|
||||
queryData: IBuilderQuery = aiQuery,
|
||||
currentQuery?: Query,
|
||||
): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryAggregationSelect queryData={queryData} />
|
||||
@@ -125,12 +126,9 @@ async function enterAggregation(
|
||||
{ queryBuilderOverrides: currentQuery && { currentQuery } },
|
||||
);
|
||||
|
||||
const content = (
|
||||
await screen.findByTestId(EDITOR_TEST_ID)
|
||||
).querySelector<HTMLElement>('.cm-content');
|
||||
if (!content) {
|
||||
throw new Error('CodeMirror content element not rendered');
|
||||
}
|
||||
const content = within(await screen.findByTestId(EDITOR_TEST_ID)).getByRole(
|
||||
'textbox',
|
||||
);
|
||||
await user.click(content);
|
||||
// Typed keys drop under load: a re-render's dispatch discards DOM input CodeMirror hasn't read yet.
|
||||
await user.paste(text);
|
||||
@@ -138,10 +136,10 @@ async function enterAggregation(
|
||||
}
|
||||
|
||||
function suggestionLabels(): string[] {
|
||||
return Array.from(
|
||||
screen.getByTestId(EDITOR_TEST_ID).querySelectorAll('.cm-completionLabel'),
|
||||
(label) => label.textContent ?? '',
|
||||
).sort();
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((option) => option.textContent ?? '')
|
||||
.sort();
|
||||
}
|
||||
|
||||
describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
@@ -161,9 +159,10 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
async ({ aggregation, fieldDataType, labels }) => {
|
||||
await enterAggregation(aggregation);
|
||||
|
||||
await waitFor(() => expect(suggestionLabels()).toStrictEqual(labels), {
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual(labels);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
expect(
|
||||
aiKeysRequests.map((params) => ({
|
||||
@@ -185,14 +184,13 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]),
|
||||
{ timeout: SUGGESTIONS_TIMEOUT_MS },
|
||||
);
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'trace.total_tokens', {
|
||||
timeout: SUGGESTIONS_TIMEOUT_MS,
|
||||
});
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findCompletionOption } from './findCompletionOption';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const CM_OPTION_SELECTOR = '.cm-tooltip-autocomplete .cm-completionLabel';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
beforeAll(() => {
|
||||
mockCodeMirrorDomApis();
|
||||
@@ -110,11 +111,7 @@ async function renderAndType(text: string): Promise<HTMLElement> {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, text);
|
||||
return editor;
|
||||
@@ -128,32 +125,26 @@ async function typeKeyThenEnterOperatorContext(
|
||||
): Promise<void> {
|
||||
const editor = await renderAndType(key);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain(expectedKeyLabel);
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, expectedKeyLabel);
|
||||
|
||||
// skipClick: a click would reset the caret to position 0 under the mocked
|
||||
// DOM rects; we need the space appended at the end of the typed key.
|
||||
await userEvent.type(editor, ' ', { skipClick: true });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('=');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, '=');
|
||||
}
|
||||
|
||||
function visibleOptionLabels(): string[] {
|
||||
return Array.from(document.querySelectorAll(CM_OPTION_SELECTOR)).map(
|
||||
(el) => el.textContent ?? '',
|
||||
);
|
||||
return within(screen.getByTestId(EDITOR_TEST_ID))
|
||||
.queryAllByRole('option')
|
||||
.map((el) => el.textContent ?? '');
|
||||
}
|
||||
|
||||
describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows one deduped suggestion per key name in normal mode', async () => {
|
||||
await renderAndType('statu');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'status.code');
|
||||
|
||||
const statusOptions = visibleOptionLabels().filter(
|
||||
(label) => label === 'status.code',
|
||||
@@ -164,9 +155,7 @@ describe('QuerySearch context-prefixed key suggestions', () => {
|
||||
it('shows context-scoped suggestions for a complete context prefix', async () => {
|
||||
await renderAndType('attribute.');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(visibleOptionLabels()).toContain('attribute.status.code');
|
||||
});
|
||||
await findCompletionOption(EDITOR_TEST_ID, 'attribute.status.code');
|
||||
|
||||
const labels = visibleOptionLabels();
|
||||
// Literal key name match ranks first
|
||||
|
||||
@@ -2,7 +2,9 @@ import { EditorView } from '@uiw/react-codemirror';
|
||||
import { getFieldKeySuggestions } from 'api/querySuggestions/getFieldKeySuggestions';
|
||||
import { getFieldValueSuggestions } from 'api/querySuggestions/getFieldValueSuggestions';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { holdResponse } from 'tests/holdResponse';
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
@@ -14,8 +16,9 @@ import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
// Mock DOM APIs that CodeMirror needs
|
||||
beforeAll(() => {
|
||||
@@ -75,8 +78,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// CodeMirror renders a contenteditable div, so we check for the container
|
||||
const editorContainer = document.querySelector('.query-where-clause-editor');
|
||||
expect(editorContainer).toBeInTheDocument();
|
||||
expect(screen.getByTestId(EDITOR_TEST_ID)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fetches key suggestions when typing a key (debounced)', async () => {
|
||||
@@ -94,14 +96,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find the CodeMirror editor contenteditable element
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
|
||||
// Focus and type into the editor
|
||||
await userEvent.click(editor);
|
||||
@@ -141,12 +137,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_VALUE_TYPING_INCOMPLETE);
|
||||
|
||||
@@ -162,6 +153,51 @@ 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<
|
||||
@@ -203,12 +239,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize
|
||||
await waitFor(() => {
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(editor).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const editor = document.querySelector(CM_EDITOR_SELECTOR) as HTMLElement;
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await userEvent.click(editor);
|
||||
await userEvent.type(editor, SAMPLE_STATUS_QUERY);
|
||||
|
||||
@@ -255,11 +286,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -268,7 +296,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
|
||||
it('shows the locked scope as a chip in place of the scope icon', () => {
|
||||
const scope = "kind_string = 'Client' AND http_host = 'api.example.com'";
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -283,12 +311,12 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
expect(chip).toHaveTextContent('+1');
|
||||
expect(chip).not.toHaveTextContent('kind_string');
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.queryByTestId('query-search-initial-scope-label'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the scope icon unless the chip is asked for', () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<QuerySearch
|
||||
onChange={jest.fn() as jest.MockedFunction<(v: string) => void>}
|
||||
queryData={initialQueriesMap.traces.builder.queryData[0]}
|
||||
@@ -301,7 +329,7 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
screen.queryByTestId('query-search-scope-chip'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
container.querySelector('.query-search-initial-scope-label'),
|
||||
screen.getByTestId('query-search-initial-scope-label'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -341,11 +369,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(document.querySelector(CM_EDITOR_SELECTOR)?.textContent).toBe(
|
||||
SAMPLE_STATUS_QUERY,
|
||||
),
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
await waitFor(() => expect(editor.textContent).toBe(SAMPLE_STATUS_QUERY));
|
||||
|
||||
await userEvent.click(screen.getByTestId('query-search-run-button'));
|
||||
|
||||
@@ -371,13 +396,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize and the expression to be set
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
// CodeMirror stores content in .cm-content, check the text content
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
// CodeMirror may render the text in multiple ways, check if it contains our expression
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toContain('http.status_code');
|
||||
@@ -412,12 +433,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
);
|
||||
|
||||
// Wait for CodeMirror to initialize with the initial expression
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent).toBeInTheDocument();
|
||||
const textContent = editorContent.textContent || '';
|
||||
expect(textContent).toBe(initialExpression);
|
||||
},
|
||||
@@ -477,11 +495,9 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const editorContent = await findQueryEditorTextbox();
|
||||
await waitFor(
|
||||
() => {
|
||||
const editorContent = document.querySelector(
|
||||
CM_EDITOR_SELECTOR,
|
||||
) as HTMLElement;
|
||||
expect(editorContent.textContent || '').toBe(initialExpression);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
|
||||
@@ -6,18 +6,22 @@ import {
|
||||
import { EditorView } from '@uiw/react-codemirror';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
|
||||
import { fireEvent, render, userEvent, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
} from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { RECENTS_DISPLAY_CAP, RECENTS_SECTION } from '../QuerySearch/constants';
|
||||
import QuerySearch from '../QuerySearch/QuerySearch';
|
||||
import { mockCodeMirrorDomApis } from './codemirrorDomMocks';
|
||||
import { findQueryEditorTextbox } from './queryEditorTextbox';
|
||||
|
||||
const CM_ROOT_SELECTOR = '.cm-editor';
|
||||
const CM_EDITOR_SELECTOR = '.cm-editor .cm-content';
|
||||
const TOOLTIP_SELECTOR = '.cm-tooltip-autocomplete';
|
||||
const COMPLETION_LABEL_SELECTOR = '.cm-completionLabel';
|
||||
const DELETE_BUTTON_SELECTOR = '.cm-recent-delete';
|
||||
const EDITOR_TEST_ID = 'query-where-clause-editor';
|
||||
|
||||
const FRONTEND_FILTER = "service.name = 'frontend'";
|
||||
const STATUS_CODE_FILTER = "http.status_code = '500'";
|
||||
@@ -68,7 +72,7 @@ function saveLogsRecent(expression: string): void {
|
||||
}
|
||||
|
||||
function getEditorView(): EditorView | null {
|
||||
const root = document.querySelector<HTMLElement>(CM_ROOT_SELECTOR);
|
||||
const root = screen.queryByTestId(EDITOR_TEST_ID);
|
||||
return root ? EditorView.findFromDOM(root) : null;
|
||||
}
|
||||
|
||||
@@ -98,14 +102,7 @@ async function renderAndFocus(
|
||||
): Promise<HTMLElement> {
|
||||
renderLogsSearch(onChange);
|
||||
|
||||
const editor = await waitFor(
|
||||
() => {
|
||||
const element = document.querySelector(CM_EDITOR_SELECTOR);
|
||||
expect(element).toBeInTheDocument();
|
||||
return element as HTMLElement;
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
const editor = await findQueryEditorTextbox();
|
||||
|
||||
await userEvent.click(editor);
|
||||
return editor;
|
||||
@@ -235,9 +232,7 @@ describe('QuerySearch recent searches', () => {
|
||||
await openRecents();
|
||||
|
||||
const option = await waitForPopupElement(() =>
|
||||
Array.from(
|
||||
document.querySelectorAll<HTMLElement>(COMPLETION_LABEL_SELECTOR),
|
||||
).find((element) => element.textContent === FRONTEND_FILTER),
|
||||
screen.queryByText(FRONTEND_FILTER),
|
||||
);
|
||||
// fireEvent: userEvent's pointerdown blurs the editor, closing the popup before CM's mousedown apply.
|
||||
fireEvent.mouseDown(option);
|
||||
@@ -253,7 +248,9 @@ describe('QuerySearch recent searches', () => {
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(document.querySelector(TOOLTIP_SELECTOR)).not.toBeInTheDocument();
|
||||
expect(
|
||||
within(screen.getByTestId(EDITOR_TEST_ID)).queryByLabelText('Completions'),
|
||||
).not.toBeInTheDocument();
|
||||
},
|
||||
{ timeout: 2000 },
|
||||
);
|
||||
@@ -266,7 +263,7 @@ describe('QuerySearch recent searches', () => {
|
||||
await openRecents();
|
||||
|
||||
const deleteButton = await waitForPopupElement(() =>
|
||||
document.querySelector<HTMLElement>(DELETE_BUTTON_SELECTOR),
|
||||
screen.queryByTestId('query-search-recent-delete'),
|
||||
);
|
||||
|
||||
// fireEvent: the button preventDefaults pointerdown, which makes userEvent.click drop the mouse chain.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { screen, within, type waitForOptions } from 'tests/test-utils';
|
||||
|
||||
export function findCompletionOption(
|
||||
editorTestId: string,
|
||||
label: string,
|
||||
options?: waitForOptions,
|
||||
): Promise<HTMLElement> {
|
||||
return within(screen.getByTestId(editorTestId)).findByText(
|
||||
(_, element) =>
|
||||
element?.getAttribute('role') === 'option' && element.textContent === label,
|
||||
undefined,
|
||||
options,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { screen, within } from 'tests/test-utils';
|
||||
|
||||
export async function findQueryEditorTextbox(): Promise<HTMLElement> {
|
||||
return within(
|
||||
await screen.findByTestId('query-where-clause-editor'),
|
||||
).getByRole('textbox');
|
||||
}
|
||||
@@ -361,7 +361,7 @@ describe('QueryAddOns', () => {
|
||||
});
|
||||
|
||||
it('calls handleSetQueryData when reduce-to value changes', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
const query = baseQuery({
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
aggregations: [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { jest } from '@jest/globals';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import {
|
||||
Having,
|
||||
IBuilderQuery,
|
||||
@@ -146,7 +146,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
});
|
||||
|
||||
it('savePreviousQuery=true: metrics → meter saves previous query in session storage with appropriate key and query', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
panelType={PANEL_TYPES.TABLE}
|
||||
@@ -155,9 +155,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
savePreviousQuery
|
||||
/>,
|
||||
);
|
||||
const trigger = document.querySelector(
|
||||
'.metrics-container .source-selector .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const trigger = within(
|
||||
screen.getByTestId('metrics-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
|
||||
await user.click(trigger);
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
});
|
||||
|
||||
it('savePreviousQuery=false: metrics → meter does not write to sessionStorage and applies defaults', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
// render WITHOUT savePreviousQuery enabled
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -193,9 +193,9 @@ describe('MetricsSelect - signal source switching (standalone)', () => {
|
||||
);
|
||||
|
||||
// open Source and choose Meter
|
||||
const trigger = document.querySelector(
|
||||
'.metrics-container .source-selector .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const trigger = within(
|
||||
screen.getByTestId('metrics-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(trigger);
|
||||
const meterOption = await screen.findByText('Meter');
|
||||
await user.click(meterOption);
|
||||
@@ -302,7 +302,7 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
});
|
||||
|
||||
it('updates query dataSource to TRACES saves previous query in session storage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -313,19 +313,12 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const logsTrigger = document.querySelector(
|
||||
'.query-data-source .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const logsTrigger = within(
|
||||
screen.getByTestId('query-data-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(logsTrigger);
|
||||
|
||||
const tracesContent = screen.getByText('Traces', {
|
||||
selector: '.ant-select-item-option-content',
|
||||
});
|
||||
|
||||
// click the option (prefer the option element; fallback to content)
|
||||
await user.click(
|
||||
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
|
||||
);
|
||||
await user.click(screen.getByTitle('Traces'));
|
||||
|
||||
// verify previousQuery store saved the current LOGS snapshot before switch
|
||||
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
|
||||
@@ -337,7 +330,7 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
);
|
||||
});
|
||||
it('updates query dataSource to TRACES does not saves previous query in session storage', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
render(
|
||||
<QueryBuilderV2
|
||||
@@ -347,19 +340,12 @@ describe('DataSource change - Logs to Traces', () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
const logsTrigger = document.querySelector(
|
||||
'.query-data-source .ant-select-selector',
|
||||
) as HTMLElement;
|
||||
const logsTrigger = within(
|
||||
screen.getByTestId('query-data-source-selector-0'),
|
||||
).getByRole('combobox');
|
||||
await user.click(logsTrigger);
|
||||
|
||||
const tracesContent = screen.getByText('Traces', {
|
||||
selector: '.ant-select-item-option-content',
|
||||
});
|
||||
|
||||
// click the option (prefer the option element; fallback to content)
|
||||
await user.click(
|
||||
(tracesContent.closest('[role="option"]') as HTMLElement) || tracesContent,
|
||||
);
|
||||
await user.click(screen.getByTitle('Traces'));
|
||||
|
||||
// Assert that no snapshot was written
|
||||
const storeRaw = sessionStorage.getItem(PREVIOUS_QUERY_KEY);
|
||||
|
||||
@@ -197,7 +197,7 @@ export default function CheckboxFilterV2(
|
||||
onClear={onClear}
|
||||
/>
|
||||
{isOpen && isLoading && !hasLoadedOnce.current && (
|
||||
<section>
|
||||
<section data-testid="checkbox-filter-skeleton">
|
||||
<Skeleton paragraph={{ rows: 4 }} />
|
||||
</section>
|
||||
)}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user