Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Clean up content library tests for code lists #14585

Merged
merged 3 commits into from
Feb 6, 2025
Merged

Conversation

TomasEng
Copy link
Contributor

@TomasEng TomasEng commented Feb 6, 2025

Description

As I am going to work in the CodeListPage test suite, I had to do some initial work to facilitate the implementation of the upcoming tests. This pull request contains the following improvements to the CodeListPage tests:

  • Moved test data to a folder named test-data, to keep the same structure as in studio-components.
  • Extended the test data with another code list and some text resources in two languages. The text resources will be useful in the upcoming tests.
  • Added some types for the test data.
  • Removed the unnecessary resetting of defaultCodeListPageProps in the afterEach hook. This was probably added because one of the tests manipulated the object for some reason. I removed that as well since it was not necessary to make the test work.
  • Removed some unnecessary toHaveAttribute checks.
  • Improved the helper functions, e.g. by adding return types and more precise naming.
  • Improved selectors by using getByRole where possible.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings

Summary by CodeRabbit

  • New Features

    • Expanded the public API with additional type definitions that enhance list management and localization support.
    • Introduced structured test data for dynamic lists and multilingual text resources, paving the way for improved functionality.
  • Tests

    • Refined test coverage and helper routines to ensure consistent behavior and reliability in list management features.

Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

Warning

Rate limit exceeded

@TomasEng has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 54 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 71b5d97 and 4679114.

📒 Files selected for processing (1)
  • frontend/libs/studio-content-library/src/test-data/codeListDataList.ts (1 hunks)
📝 Walkthrough

Walkthrough

This pull request extends the public API and test utility structure in the frontend libraries. It adds exports for the TextResource type and introduces new type definitions for code list data and text resources. The PR also supplies new test-data files for code lists and text localization, and updates the CodeListPage tests with revised imports, variable names, function signatures, and helper functions. These changes standardize and consolidate type definitions and test data management without modifying existing functionality.

Changes

File(s) Change Summary
frontend/libs/studio-components/src/index.ts &
frontend/libs/studio-content-library/src/types/{CodeList.ts, TextResource.ts, CodeListData.ts, TextResources.ts}
Added export for TextResource and introduced new type definitions: exported CodeList, added CodeListData and TextResources for structured code list and localization support.
frontend/libs/studio-content-library/src/test-data/{codeListDataList.ts, textResources.ts} Introduced new test data: defined code lists (codeList1Data, codeList2Data, codeListDataList) and added text localization constants and exports for Norwegian and English.
frontend/libs/studio-content-library/src/.../CodeListPage.test.tsx Updated tests for the CodeListPage component, including new imports, renaming mock variables, updating default props, modifying function signatures, and adding helper functions for element retrieval.

Possibly related PRs

Suggested reviewers

  • github-actions
  • mlqn

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. frontend labels Feb 6, 2025
@TomasEng TomasEng changed the title Clean up content library tests test: Clean up content library tests for code lists Feb 6, 2025
Copy link

codecov bot commented Feb 6, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.74%. Comparing base (e2cdf67) to head (4679114).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14585      +/-   ##
==========================================
+ Coverage   95.73%   95.74%   +0.01%     
==========================================
  Files        1906     1908       +2     
  Lines       24844    24915      +71     
  Branches     2848     2848              
==========================================
+ Hits        23785    23856      +71     
  Misses        799      799              
  Partials      260      260              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@TomasEng TomasEng added team/studio-domain1 quality/testing Tests that are missing, needs to be created or could be improved. area/content-library Area: Related to library for shared resources skip-releasenotes Issues that do not make sense to list in our release notes skip-manual-testing PRs that do not need to be tested manually skip-documentation Issues where updating documentation is not relevant labels Feb 6, 2025
@TomasEng TomasEng marked this pull request as ready for review February 6, 2025 07:12
Copy link
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: 0

🧹 Nitpick comments (8)
frontend/libs/studio-content-library/src/test-data/codeListDataList.ts (3)

10-29: Consider reducing code duplication in codeList1.

The items in codeList1 have identical properties except for the value. Consider using a helper function or array mapping to generate these items.

Example refactor:

-const codeList1: CodeList = [
-  {
-    value: 'item1',
-    label: label1ResourceNb.id,
-    description: description1ResourceNb.id,
-    helpText: helpText1ResourceNb.id,
-  },
-  {
-    value: 'item2',
-    label: label1ResourceNb.id,
-    description: description1ResourceNb.id,
-    helpText: helpText1ResourceNb.id,
-  },
-  {
-    value: 'item3',
-    label: label1ResourceNb.id,
-    description: description1ResourceNb.id,
-    helpText: helpText1ResourceNb.id,
-  },
-];
+const createCodeListItem = (value: string) => ({
+  value,
+  label: label1ResourceNb.id,
+  description: description1ResourceNb.id,
+  helpText: helpText1ResourceNb.id,
+});
+
+const codeList1: CodeList = ['item1', 'item2', 'item3'].map(createCodeListItem);

12-15: Consider using enums or constants for item values.

The value properties use magic strings ('item1', 'item2', etc.). Consider using an enum or constants to prevent typos and improve maintainability.

Example:

enum CodeListItems {
  Item1 = 'item1',
  Item2 = 'item2',
  Item3 = 'item3',
  Item4 = 'item4',
}

Also applies to: 38-40, 42-44


1-53: Add documentation for test data purpose.

Consider adding JSDoc comments to explain the purpose of these test data sets and how they should be used in tests.

Example:

/**
 * Test data for code lists used in CodeListPage tests.
 * codeList1: Complete code list with all optional fields
 * codeList2: Minimal code list with only required fields
 */
frontend/libs/studio-content-library/src/test-data/textResources.ts (3)

4-15: Consider using an enum for text IDs.

The text IDs could be better organized using an enum to provide better type safety and autocompletion.

-const label1Id = 'label1';
-const description1Id = 'description1';
-const helpText1Id = 'helpText1';
-const label2Id = 'label2';
-const description2Id = 'description2';
-const helpText2Id = 'helpText2';
-const label3Id = 'label3';
-const description3Id = 'description3';
-const helpText3Id = 'helpText3';
-const label4Id = 'label4';
-const description4Id = 'description4';
-const helpText4Id = 'helpText4';
+enum TextId {
+  Label1 = 'label1',
+  Description1 = 'description1',
+  HelpText1 = 'helpText1',
+  Label2 = 'label2',
+  Description2 = 'description2',
+  HelpText2 = 'helpText2',
+  Label3 = 'label3',
+  Description3 = 'description3',
+  HelpText3 = 'helpText3',
+  Label4 = 'label4',
+  Description4 = 'description4',
+  HelpText4 = 'helpText4',
+}

16-39: Consider using a record for text values.

The text values could be better organized using a record to group related translations and reduce repetition.

-const label1Nb = 'Ledetekst 1';
-const description1Nb = 'Beskrivelse 1';
-const helpText1Nb = 'Hjelpetekst 1';
-// ... more Norwegian text
-const label1En = 'Label 1';
-const description1En = 'Description 1';
-const helpText1En = 'Help text 1';
-// ... more English text
+const textValues = {
+  nb: {
+    label1: 'Ledetekst 1',
+    description1: 'Beskrivelse 1',
+    helpText1: 'Hjelpetekst 1',
+    // ... more Norwegian text
+  },
+  en: {
+    label1: 'Label 1',
+    description1: 'Description 1',
+    helpText1: 'Help text 1',
+    // ... more English text
+  },
+} as const;

41-64: Consider using a factory function for text resources.

The individual text resource exports could be simplified using a factory function to reduce repetition.

+const createTextResource = (id: TextId, value: string): TextResource => ({ id, value });

-export const label1ResourceNb: TextResource = { id: label1Id, value: label1Nb };
-export const label1ResourceEn: TextResource = { id: label1Id, value: label1En };
-// ... more text resources
+export const label1ResourceNb = createTextResource(TextId.Label1, textValues.nb.label1);
+export const label1ResourceEn = createTextResource(TextId.Label1, textValues.en.label1);
// ... more text resources
frontend/libs/studio-content-library/src/ContentLibrary/LibraryBody/pages/CodeListPage/CodeListPage.test.tsx (2)

29-158: Consider using test.each for similar test cases.

Some test cases follow similar patterns and could be refactored using test.each to reduce code duplication.

+const testCases = [
+  {
+    name: 'renders the codeList heading',
+    setup: () => ({
+      selector: { role: 'heading', name: textMock('app_content_library.code_lists.page_name') },
+    }),
+  },
+  {
+    name: 'renders a code list counter message',
+    setup: () => ({
+      selector: { text: textMock('app_content_library.code_lists.code_lists_count_info_plural') },
+    }),
+  },
+];
+
+test.each(testCases)('$name', ({ setup }) => {
+  const { selector } = setup();
+  renderCodeListPage();
+  const element = selector.role
+    ? screen.getByRole(selector.role, { name: selector.name })
+    : screen.getByText(selector.text);
+  expect(element).toBeInTheDocument();
+});

160-181: Consider adding return type for renderCodeListPage.

The renderCodeListPage helper function should have an explicit return type for better type safety.

-const renderCodeListPage = (props: Partial<CodeListPageProps> = {}): RenderResult =>
+const renderCodeListPage = (props: Partial<CodeListPageProps> = {}): RenderResult & { rerender: (ui: React.ReactElement) => void } =>

Also, consider adding JSDoc comments to document the helper functions' purposes and parameters.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2cdf67 and 71b5d97.

📒 Files selected for processing (8)
  • frontend/libs/studio-components/src/index.ts (1 hunks)
  • frontend/libs/studio-content-library/src/ContentLibrary/LibraryBody/pages/CodeListPage/CodeListPage.test.tsx (3 hunks)
  • frontend/libs/studio-content-library/src/test-data/codeListDataList.ts (1 hunks)
  • frontend/libs/studio-content-library/src/test-data/textResources.ts (1 hunks)
  • frontend/libs/studio-content-library/src/types/CodeList.ts (1 hunks)
  • frontend/libs/studio-content-library/src/types/CodeListData.ts (1 hunks)
  • frontend/libs/studio-content-library/src/types/TextResource.ts (1 hunks)
  • frontend/libs/studio-content-library/src/types/TextResources.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/libs/studio-content-library/src/types/CodeList.ts
  • frontend/libs/studio-content-library/src/types/TextResource.ts
🔇 Additional comments (8)
frontend/libs/studio-content-library/src/types/TextResources.ts (1)

1-5: LGTM! Clean type definition.

The TextResources type definition is well-structured and provides good type safety for managing text resources across different languages.

frontend/libs/studio-content-library/src/types/CodeListData.ts (1)

1-7: LGTM! Well-structured type definition.

The CodeListData type definition is clear and provides good flexibility with optional fields for data and error handling.

frontend/libs/studio-components/src/index.ts (1)

6-6: LGTM! Clean type export.

The TextResource type export is correctly added and maintains consistency with existing export patterns.

frontend/libs/studio-content-library/src/test-data/codeListDataList.ts (1)

36-45: Consider consistent structure between code lists.

codeList2 items have inconsistent structure compared to codeList1 items. Consider documenting why this inconsistency exists if it's intentional for testing purposes.

Is this structural difference intentional for testing different scenarios? If so, consider adding a comment explaining the purpose.

frontend/libs/studio-content-library/src/test-data/textResources.ts (2)

1-2: LGTM!

The imports are correctly typed and properly scoped.


66-99: LGTM!

The text resource arrays and final export are well-organized and properly typed.

frontend/libs/studio-content-library/src/ContentLibrary/LibraryBody/pages/CodeListPage/CodeListPage.test.tsx (2)

1-27: LGTM!

The imports are well-organized, and the mock setup is clear and properly typed.


168-171: Consider using data-testid for accordion element.

The comment indicates that accessing the accordion element through parentElement is not recommended. Instead of waiting for the Design System upgrade, consider adding a data-testid attribute to the accordion element as a temporary solution.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check if the accordion element is already using data-testid in other files

# Search for data-testid usage in accordion elements
rg -i "data-testid.*accordion"

# Search for the accordion component definition
ast-grep --pattern 'const Accordion = ({ children }) => {
  $$$
}'

Length of output: 386


Use data-testid for accordion element as in other parts of the codebase.
The search results confirmed that other accordion components (e.g., in frontend/packages/ux-editor-v3/src/containers/DesignView/PageAccordion/PageAccordion.tsx and frontend/packages/ux-editor/src/containers/DesignView/PageAccordion/PageAccordion.tsx) already utilize data-testid attributes for testing purposes. Adopting a similar approach in the CodeListPage test is a good temporary solution until the Design System upgrade is performed.

@wrt95 wrt95 self-assigned this Feb 6, 2025
Copy link
Contributor

@wrt95 wrt95 left a comment

Choose a reason for hiding this comment

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

🥳

@wrt95 wrt95 merged commit 2e6d8db into main Feb 6, 2025
11 checks passed
@wrt95 wrt95 deleted the clean-library-tests branch February 6, 2025 08:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/content-library Area: Related to library for shared resources frontend quality/testing Tests that are missing, needs to be created or could be improved. skip-documentation Issues where updating documentation is not relevant skip-manual-testing PRs that do not need to be tested manually skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution. team/studio-domain1
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants