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

feat: create frontend mock endpoint for get codelists #14513

Closed

Conversation

wrt95
Copy link
Contributor

@wrt95 wrt95 commented Jan 27, 2025

Description

  • Creating mock endpoint in frontend for get code lists

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for fetching organizational level code lists.
    • Introduced a new custom hook for retrieving code lists.
    • Expanded query key enumeration to support new code list queries.
  • Chores

    • Added mock implementations for testing and development purposes.

The changes enhance the application's data retrieval capabilities for organizational code lists with a new query mechanism.

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Warning

Rate limit exceeded

@wrt95 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 36 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 a064d1e and 6b89cc1.

📒 Files selected for processing (3)
  • frontend/packages/shared/src/api/queries.ts (1 hunks)
  • frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.test.ts (1 hunks)
  • frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.ts (1 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces functionality for organizational level code lists across multiple frontend files. It adds a new mock implementation for fetching code lists, creates a custom query hook, updates the query key enum, and provides a Jest mock function for testing. The changes prepare the groundwork for retrieving and managing organizational level code lists with a placeholder implementation that can be replaced with a backend endpoint in the future.

Changes

File Change Summary
frontend/packages/shared/src/api/queries.ts - Added import for CodeList type
- Created orgLevelCodeListsMock constant
- Implemented getOrgLevelCodeLists async function
frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.ts - Added new custom hook useOrgLevelCodeListsQuery
- Uses useQuery to fetch organizational level code lists
frontend/packages/shared/src/mocks/queriesMock.ts - Added getOrgLevelCodeLists Jest mock function
- Returns an empty array promise
frontend/packages/shared/src/types/QueryKey.ts - Added new enum entry OrgLevelCodeLists

Possibly related PRs

Suggested labels

area/content-library, quality/testing, skip-manual-testing

Suggested reviewers

  • Jondyr
  • github-actions

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 Jan 27, 2025
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 (1)
frontend/packages/shared/src/api/queries.ts (1)

205-213: Consider enhancing the mock implementation.

A few suggestions:

  1. The commented code for testing empty lists could be moved to a separate exported constant for better reusability.
  2. Consider adding a mock for error scenarios to test error handling in the UI.

Here's a suggested implementation:

+const emptyCodeListsMock: CodeList[] = [];
+
 export const getOrgLevelCodeLists = async (): Promise<CodeList[]> =>
   // TODO: Replace with endpoint when it is ready in backend.
   new Promise((resolve) => {
     setTimeout(() => {
-      // Replace the two resolves to test with empty list
-      // resolve([]);
       resolve(orgLevelCodeListsMock);
     }, 1000);
   });
+
+// Export for testing
+export const mockEmptyResponse = async (): Promise<CodeList[]> =>
+  Promise.resolve(emptyCodeListsMock);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bed2631 and 246c924.

📒 Files selected for processing (4)
  • frontend/packages/shared/src/api/queries.ts (2 hunks)
  • frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.ts (1 hunks)
  • frontend/packages/shared/src/mocks/queriesMock.ts (1 hunks)
  • frontend/packages/shared/src/types/QueryKey.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
🔇 Additional comments (4)
frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.ts (1)

6-12: Well-structured React Query implementation!

The custom hook follows best practices with proper typing and clean implementation.

frontend/packages/shared/src/types/QueryKey.ts (1)

52-52: LGTM!

The new enum entry follows the existing pattern and maintains alphabetical ordering.

frontend/packages/shared/src/api/queries.ts (1)

181-204: Mock data provides good test coverage.

The mock data includes different value types (string, boolean, number) and varying array lengths, which is good for testing different scenarios.

frontend/packages/shared/src/mocks/queriesMock.ts (1)

80-80: LGTM!

The Jest mock follows the existing pattern and maintains consistency with other mocks.

Copy link

codecov bot commented Jan 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 95.70%. Comparing base (3a133e6) to head (6b89cc1).
Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14513   +/-   ##
=======================================
  Coverage   95.69%   95.70%           
=======================================
  Files        1902     1903    +1     
  Lines       24715    24723    +8     
  Branches     2829     2829           
=======================================
+ Hits        23652    23660    +8     
  Misses        802      802           
  Partials      261      261           

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

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: 1

🧹 Nitpick comments (1)
frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.test.ts (1)

14-18: Improve render helper function flexibility.

The current implementation always waits for success state, which won't work for testing error scenarios. Also, consider adding TypeScript return type annotation.

Consider applying this diff:

-const render = async () => {
+const render = async (waitForSuccess = true) => {
   const { result } = renderHookWithProviders(() => useOrgLevelCodeListsQuery());
-  await waitFor(() => expect(result.current.isSuccess).toBe(true));
+  if (waitForSuccess) {
+    await waitFor(() => expect(result.current.isSuccess).toBe(true));
+  }
   return result;
-};
+} as const;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 246c924 and a064d1e.

📒 Files selected for processing (1)
  • frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
🔇 Additional comments (1)
frontend/packages/shared/src/hooks/queries/useOrgLevelCodeListsQuery.test.ts (1)

1-4: LGTM! All necessary imports are present.

The imports cover all required testing utilities and mock implementations.

Comment on lines 6 to 12
describe('useOrgLevelCodeListsQuery', () => {
it('calls getOptionListsReferences with the correct parameters', () => {
render();
expect(queriesMock.getOrgLevelCodeLists).toHaveBeenCalledWith();
expect(queriesMock.getOrgLevelCodeLists).toHaveBeenCalledTimes(1);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage and fix test description.

The current test suite has several areas for improvement:

  1. The test description mentions "getOptionListsReferences" but tests "getOrgLevelCodeLists"
  2. Missing test cases for:
    • Verifying the returned data structure
    • Error handling
    • Loading states

Consider applying this diff:

 describe('useOrgLevelCodeListsQuery', () => {
-  it('calls getOptionListsReferences with the correct parameters', () => {
+  it('calls getOrgLevelCodeLists and returns the code lists data', () => {
     render();
     expect(queriesMock.getOrgLevelCodeLists).toHaveBeenCalledWith();
     expect(queriesMock.getOrgLevelCodeLists).toHaveBeenCalledTimes(1);
+    expect(result.current.data).toEqual(expect.any(Array));
   });
+
+  it('handles error states correctly', async () => {
+    queriesMock.getOrgLevelCodeLists.mockRejectedValueOnce(new Error('Failed to fetch'));
+    const { result } = renderHookWithProviders(() => useOrgLevelCodeListsQuery());
+    await waitFor(() => expect(result.current.isError).toBe(true));
+    expect(result.current.error).toBeDefined();
+  });
+
+  it('shows loading state while fetching data', () => {
+    const { result } = renderHookWithProviders(() => useOrgLevelCodeListsQuery());
+    expect(result.current.isLoading).toBe(true);
+  });
 });

Committable suggestion skipped: line range outside the PR's diff.

@TomasEng TomasEng self-assigned this Jan 27, 2025
Copy link
Contributor

Choose a reason for hiding this comment

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

Vi har en egen sak for hooks (#14505), så du må gjerne flytte dette ut i en separat PR.


// Org level code lists

const orgLevelCodeListsMock: CodeList[] = [
Copy link
Contributor

Choose a reason for hiding this comment

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

Responsen bør også inneholde tittel på kodelistene. Jeg foreslår at vi bruker typen OptionListsResponse her. Da blir det likt som det vi bruker på appnivå.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Som snakket om på Slack så brukte jeg feil type opprinnelig 😅 Det endres nå

},
],
];
export const getOrgLevelCodeLists = async (): Promise<CodeList[]> =>
Copy link
Contributor

Choose a reason for hiding this comment

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

Denne bør ta imot org som parameter. Det er ikke så farlig at den ikke blir brukt i mocken.

],
];
export const getOrgLevelCodeLists = async (): Promise<CodeList[]> =>
// TODO: Replace with endpoint when it is ready in backend.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
// TODO: Replace with endpoint when it is ready in backend.
// TODO: Replace with endpoint when it is ready in backend. https://github.com/Altinn/altinn-studio/issues/14482

Comment on lines 209 to 210
// Replace the two resolves to test with empty list
// resolve([]);
Copy link
Contributor

Choose a reason for hiding this comment

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

Skal denne kommentaren være her?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Kan fjernes

// Replace the two resolves to test with empty list
// resolve([]);
resolve(orgLevelCodeListsMock);
}, 1000);
Copy link
Contributor

@TomasEng TomasEng Jan 27, 2025

Choose a reason for hiding this comment

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

Godt tenkt å simulere treghet i responsen, men et helt sekund er kanskje litt lenge? Det kan det jo bli litt tungt å jobbe med. Har du vurdert kortere tid, typ 100-200 millisekunder?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Satt bare det tallet vi brukte på Ansattporten. Er helt samme for min del, så kan endre til 200 😄

@TomasEng TomasEng assigned wrt95 and unassigned TomasEng Jan 27, 2025
@TomasEng
Copy link
Contributor

Closing this as it will be fixed during today's workshop.

@TomasEng TomasEng closed this Jan 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
frontend 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