Skip to content

Improve shared expression tests#4041

Merged
olemartinorg merged 2 commits intomainfrom
shared-functions-tests-improvements
Mar 4, 2026
Merged

Improve shared expression tests#4041
olemartinorg merged 2 commits intomainfrom
shared-functions-tests-improvements

Conversation

@TomasEng
Copy link
Copy Markdown
Contributor

@TomasEng TomasEng commented Mar 4, 2026

Description

When the testCases property in the shared expression tests is set, all of the tests are run within the same it block. As a consequence, when one of them fails, it is not possible to see which one it is and why it fails. This pull request fixes that, so that each test case is run separately. It also moves some code into separate functions to make it more readable. Most of the changed lines in the diff are indeed just moved from another place.

We will need this when implementing the arithmetic operation functions.

Related Issue(s)

Verification/QA

  • Manual functionality testing
    • I have tested these changes manually
  • Automated tests
    • No automatic tests are needed here (no functional changes/additions)
  • UU/WCAG (follow these guidelines until we have our own)
    • No testing done/necessary (no DOM/visual changes)
  • User documentation @ altinn-studio-docs
    • No functionality has been changed/added, so no documentation is needed
  • Support in Altinn Studio
    • This change/feature does not require any changes to Altinn Studio
  • Sprint board
    • The original issue (or this PR itself) has been added to the Team Apps project and to the current sprint board
  • Labels
    • I have added a kind/* and backport* label to this PR for proper release notes grouping

Summary by CodeRabbit

  • Tests
    • Reworked the expressions test harness to be data-driven and modular, centralizing mock/setup helpers and test rendering orchestration to improve maintainability and clarity.
    • Adjusted TypeScript type imports and organization within tests (no runtime API changes).

Note: Internal test and typing improvements only; no changes to end-user functionality.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 4, 2026

📝 Walkthrough

Walkthrough

Refactors the expressions/shared-functions test harness into a data-driven, modular structure with centralized mock factories, a single setupMocks(), and a renderExpression() orchestration; also reorganizes TypeScript type-only imports and adjusts some package/manifest metadata.

Changes

Cohort / File(s) Summary
Test harness (primary)
src/features/expressions/shared-functions.test.tsx
Complete rewrite of the test file to a data-driven, modular harness: replaces per-folder iteration with getAllTestCases(test) flow, introduces renderExpression(test, expression), and centralizes mocking via setupMocks() and factory helpers (createApplicationMetadata, createProcess, createProfile, createInstanceData, createInstance).
Test helpers / query/layout composition
src/features/expressions/...
Adds helper functions to compose AppQueries and layouts: createQueries(test, expression), createLayouts/layout augmentation, getDefaultLayouts, extractMainTestCase, and refined layout/datamodel loading driven by test inputs.
Type imports & typings
src/features/expressions/shared (imports in test)
Switches several imports to type-only (FunctionTestBase, SharedTestFunctionContext, FunctionTest, plus IncomingApplicationMetadata, IData, IDataType, IInstance, IProcess, IProfile) and reorganizes import statements without changing runtime public APIs.
Repo metadata
manifest_file, package.json
Non-test metadata/manifest changes present (lines changed alongside the test rewrite).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Improve shared expression tests' directly aligns with the main change—refactoring the test harness to run each test case separately for better failure visibility.
Description check ✅ Passed The pull request description follows the required template with all sections completed, including clear explanation of changes, related issue, and comprehensive verification/QA checklist.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch shared-functions-tests-improvements

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@TomasEng TomasEng added the kind/other Pull requests containing chores/repo structure/other changes label Mar 4, 2026
@TomasEng TomasEng added ignore-for-release Pull requests to be ignored in release notes backport-ignore This PR is a new feature and should not be cherry-picked onto release branches labels Mar 4, 2026
@TomasEng TomasEng force-pushed the shared-functions-tests-improvements branch 4 times, most recently from 64bb054 to 98503bc Compare March 4, 2026 13:54
@TomasEng TomasEng force-pushed the shared-functions-tests-improvements branch from 98503bc to a0a602e Compare March 4, 2026 14:10
@TomasEng
Copy link
Copy Markdown
Contributor Author

TomasEng commented Mar 4, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 4, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@TomasEng TomasEng moved this to 👷 In progress in Team Altinn Studio Mar 4, 2026
@TomasEng TomasEng added squad/data Issues that belongs to the named squad. area/test related to automated and functional testing labels Mar 4, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/features/expressions/shared-functions.test.tsx (1)

294-307: Please align test rendering with the repository test utility guideline.

This test now routes through renderWithoutInstanceAndLayout / renderWithInstanceAndLayout for form layout context scenarios. If these do not delegate to renderWithProviders, this diverges from the guideline.

As per coding guidelines, **/*.test.{ts,tsx}: Use renderWithProviders from src/test/renderWithProviders.tsx when testing components that require form layout context.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/features/expressions/shared-functions.test.tsx` around lines 294 - 307,
The test is using renderWithoutInstanceAndLayout / renderWithInstanceAndLayout
for FormLayout scenarios which may bypass the repo guideline; replace or adjust
these calls to use renderWithProviders from src/test/renderWithProviders.tsx (or
ensure those helpers delegate to renderWithProviders) so components needing form
layout context are wrapped consistently; update the calls in
shared-functions.test.tsx (where renderWithoutInstanceAndLayout and
renderWithInstanceAndLayout are invoked) to call renderWithProviders with the
appropriate initialPage/context (or modify those helpers to internally call
renderWithProviders) so the test aligns with the repository test utility
guideline.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/features/expressions/shared-functions.test.tsx`:
- Around line 389-390: The current statefulDataElementId extraction uses a
restrictive regex ([a-f0-9-]+) in the declaration of statefulDataElementId which
fails for non-hex IDs (e.g., 'abc'); update the regex used in the
statefulDataElementId assignment to match any reasonable ID token instead of
only hex (for example use a pattern that captures all characters up to the next
? or & or /), so statefulDataElementId = url.match(/data\/([^?&/]+)\?/)?.[1]
(adjust exact delimiter choices as needed) while leaving statelessDataType
untouched.
- Around line 164-166: The ternary in extractMainTestCase drops valid falsy
expressions like 0, false, and '' because it checks truthiness; update the guard
to only treat null/undefined as missing (e.g., change the condition to check
expression != null or expression !== undefined && expression !== null) so
extractMainTestCase({ expression, expects, expectsFailure }: FunctionTest)
returns { expression, expects, expectsFailure } for falsy-but-valid values;
locate the extractMainTestCase function and adjust its conditional accordingly
to return FunctionTestBase when expression is present even if falsy.
- Around line 174-175: Replace the unsafe type casts in the test setup by
returning fully shaped objects instead of casting: remove casts on
jest.mocked(fetchApplicationMetadata) and jest.mocked(useExternalApis) and
supply a proper ExternalApisResult (e.g., test.externalApis ?? { data: {},
errors: {} }); for places referencing IDataType (the map function at the lines
noted) return objects that include allowedContentTypes, maxCount, and minCount
or annotate the map's return type explicitly so TypeScript infers IDataType
correctly; likewise provide all required IData fields where the IData cast was
used and let inference determine the type for the value at line 361 instead of
casting. Ensure createApplicationMetadata/test helpers produce complete shapes
and update the mocks (fetchApplicationMetadata, useExternalApis) and any map
callbacks to return fully populated objects rather than using "as" casts.

---

Nitpick comments:
In `@src/features/expressions/shared-functions.test.tsx`:
- Around line 294-307: The test is using renderWithoutInstanceAndLayout /
renderWithInstanceAndLayout for FormLayout scenarios which may bypass the repo
guideline; replace or adjust these calls to use renderWithProviders from
src/test/renderWithProviders.tsx (or ensure those helpers delegate to
renderWithProviders) so components needing form layout context are wrapped
consistently; update the calls in shared-functions.test.tsx (where
renderWithoutInstanceAndLayout and renderWithInstanceAndLayout are invoked) to
call renderWithProviders with the appropriate initialPage/context (or modify
those helpers to internally call renderWithProviders) so the test aligns with
the repository test utility guideline.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b6ceeb28-7f13-4d93-962c-5e96df716b64

📥 Commits

Reviewing files that changed from the base of the PR and between e4aad7d and a0a602e.

📒 Files selected for processing (1)
  • src/features/expressions/shared-functions.test.tsx

Comment thread src/features/expressions/shared-functions.test.tsx
Comment thread src/features/expressions/shared-functions.test.tsx
Comment thread src/features/expressions/shared-functions.test.tsx
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Mar 4, 2026

@TomasEng TomasEng marked this pull request as ready for review March 4, 2026 19:28
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/features/expressions/shared-functions.test.tsx`:
- Around line 325-327: The regex used to extract the codeListId from url (const
codeListId = url.match(/api\/options\/(\w+)\?/)?.[1];) is too restrictive
because (\w+) excludes hyphens and other valid characters; update that match to
capture a wider set (for example use /api\/options\/([^/?]+)\?/ or
/api\/options\/([-\\w]+)\?/ ) so codeListId correctly matches IDs with hyphens
or non-alphanumeric chars and the subsequent lookup (codeLists[codeListId])
works as expected.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c9a00818-2706-4d1a-a1c9-9596f4a8adb2

📥 Commits

Reviewing files that changed from the base of the PR and between a0a602e and 1270bcf.

📒 Files selected for processing (1)
  • src/features/expressions/shared-functions.test.tsx

Comment thread src/features/expressions/shared-functions.test.tsx
@TomasEng TomasEng moved this from 👷 In progress to 🔎 In review in Team Altinn Studio Mar 4, 2026
Copy link
Copy Markdown
Contributor

@olemartinorg olemartinorg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great stuff! 🚀

@olemartinorg olemartinorg merged commit 5e931c9 into main Mar 4, 2026
24 checks passed
@github-project-automation github-project-automation Bot moved this from 🔎 In review to ✅ Done in Team Altinn Studio Mar 4, 2026
@olemartinorg olemartinorg deleted the shared-functions-tests-improvements branch March 4, 2026 21:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/test related to automated and functional testing backport-ignore This PR is a new feature and should not be cherry-picked onto release branches ignore-for-release Pull requests to be ignored in release notes kind/other Pull requests containing chores/repo structure/other changes squad/data Issues that belongs to the named squad.

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants