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(old-age-pension): Add e2e tests #16369

Closed
wants to merge 214 commits into from
Closed

Conversation

veronikasif
Copy link
Member

@veronikasif veronikasif commented Oct 11, 2024

...

Attach a link to issue if relevant

What

Specify what you're trying to achieve

Why

Specify why you need to achieve this

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced mock responses for parental leave functionalities to enhance testing capabilities.
    • Added a new set of mock responses for the Social Insurance Administration to facilitate API testing.
    • Introduced mock responses for the National Registry service to improve testing scenarios.
    • Centralized mock initialization by streamlining the setup process for various services.
  • Bug Fixes

    • Improved the structure and flow of parental leave application tests for better reliability.

karenbjorg and others added 30 commits June 13, 2023 14:35
* feat(oldAgePension): period screen

* added unitest for oldAgePensionUtils

* added validator and snemmtöku additional documents

* chore: Gitbook update dirty files

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
* add validators

* validator text message
* added fisherman and additional files screen

* change id name

* format

* add to Review page
* feat(old-age-pension): added homeAllowence

* feat(old-age-pension): move to Section
* fix(old-age-pension): fishermen period

* fix(old-age-pension): fix attachments

* fix(old-age-pension): corrected homeAllowance objects

* fix(old-age-pension): fix homeAllowance screens
@veronikasif veronikasif requested review from a team as code owners October 11, 2024 12:10
Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

This pull request introduces several mock files and updates related to the parental leave and social insurance functionalities within the application. New mock responses are created for the parental leave and social insurance administration services, while a new mock file for the National Registry is also added. The setup-xroad.mocks.ts file is modified to centralize the mock setup process by calling the new mock-loading functions, enhancing the structure of the testing framework without altering existing logic.

Changes

File Change Summary
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts New file introducing mock responses for parental leave functionalities, including the loadParentalLeaveXroadMocks function.
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts Updated file enhancing mock responses for Social Insurance Administration, including the loadSocialInsuranceAdministrationXroadMocks function.
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/nationalRegistry.mocks.ts New file introducing mock responses for the National Registry service, including the loadNationalRegistryXroadMocks function.
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts Modified to centralize mock setup by calling the new mock-loading functions for parental leave, social insurance, and national registry.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • Valur

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 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.

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.

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

🧹 Outside diff range and nitpick comments (13)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts (3)

12-40: LGTM with suggestion: Consider parameterizing the kennitala

The mock setup for fetching personal information from the National Registry is well-structured and comprehensive. However, to improve test flexibility, consider parameterizing the kennitala (currently hardcoded as '0101303019') to allow for different test scenarios.

You could modify the function to accept a parameter:

export const loadParentalLeaveXroadMocks = async (kennitala: string = '0101303019') => {
  // Use `kennitala` instead of hardcoded value in all mock setups
  // ...
}

This change would allow for more diverse test cases without altering the core mock structure.


53-111: LGTM with suggestion: Consider deterministic randomness for reproducibility

The Labor service mocks are comprehensive, covering various scenarios including parental leave periods, parental leaves list (with both GET and POST methods), and pregnancy status. The use of a random factor for the expected date of birth adds variability to the tests, which is good.

However, for better test reproducibility, consider using a seeded random number generator. This would allow for controlled variability that can be reproduced when needed.

You could implement a seeded random number generator like this:

import seedrandom from 'seedrandom';

// At the beginning of the function
const rng = seedrandom('your-seed-here');

// Replace Math.random() with rng()
const babyBDayRandomFactor = Math.ceil(rng() * 85);

This approach would maintain test variability while allowing for reproducibility when needed.


1-112: Overall: Well-structured and comprehensive mock setup with room for minor improvements

This file provides a robust set of mocks for testing parental leave functionalities, covering both National Registry and Labor service endpoints. The consistent structure and comprehensive coverage of various scenarios make this an excellent foundation for e2e testing.

To further enhance this implementation, consider the following improvements:

  1. Parameterize the kennitala to allow for more flexible testing scenarios.
  2. Implement a seeded random number generator for the pregnancy status mock to balance variability with reproducibility.

These changes would make the tests more flexible and easier to debug while maintaining their thoroughness.

libs/application/templates/social-insurance-administration/old-age-pension/src/forms/Prerequisites.ts (2)

64-64: LGTM! Consider using a constant for the data-test-id.

The addition of dataTestId improves the testability of the form. Good job!

Consider defining these test IDs as constants in a separate file to ensure consistency across the codebase and ease future updates. For example:

// testIds.ts
export const OLD_AGE_PENSION_TEST_ID = 'old-age-pension';

// Usage in this file
import { OLD_AGE_PENSION_TEST_ID } from './testIds';

// ...
dataTestId: OLD_AGE_PENSION_TEST_ID,

82-82: LGTM! Completes the set of test IDs for radio options.

The addition of dataTestId for the sailor pension option completes the set of test IDs for all radio options in this form field. This consistency will greatly improve the testability of the form.

Now that all radio options have test IDs, consider updating your end-to-end tests to utilize these IDs for more robust and maintainable tests. This will make your tests less brittle to changes in the UI text or structure.

For example, in your e2e tests:

cy.get('[data-test-id="old-age-pension"]').click();
cy.get('[data-test-id="half-old-age-pension"]').should('be.visible');
cy.get('[data-test-id="sailor-pension"]').should('be.visible');
libs/application/templates/social-insurance-administration/old-age-pension/src/forms/OldAgePensionForm.ts (1)

Line range hint 1-1010: Consider improving modularity and type safety

While the current implementation is functional, there are a few suggestions to enhance maintainability and type safety:

  1. Modularity: The form definition is quite large. Consider splitting it into smaller, more manageable pieces. Each section could be defined in a separate file and then composed in this main file.

  2. Reusability: Identify common patterns or field configurations that could be extracted into reusable functions or constants. This could help reduce duplication and make updates easier.

  3. Type safety: Consider using TypeScript enums or const objects for the numerous string literals used as IDs and titles. This would provide better type checking and make refactoring easier.

Example of improving type safety:

enum FormFields {
  PaymentInfo = 'paymentInfo',
  PersonalAllowanceUsage = 'personalAllowanceUsage',
  // ... other fields
}

// Usage
buildTextField({
  id: `${FormFields.PaymentInfo}.${FormFields.PersonalAllowanceUsage}`,
  // ... other properties
})

These changes could significantly improve the maintainability and robustness of the form definition.

apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (5)

185-185: Translate TODO comment to English

The TODO comment is not in English. For consistency, please translate comments to English to ensure all team members can understand and address them.


90-95: Use consistent heading locators

Throughout the test, headings are located using page.getByRole('heading', { name: ... }). Ensure that this pattern is consistently used for readability and maintainability.


20-20: Use realistic test data for phone number

The phone number '0103019' may not conform to typical phone number formats. Consider using a realistic test phone number to better simulate real-world scenarios.


151-161: Clarify selection for "One payment per year"

The test selects "No" for the "One payment per year" option. Ensure this choice aligns with the test scenario expectations, and consider adding a comment to explain the selection if necessary.


194-194: Remove unnecessary commented-out code

The code is commented out and may no longer be needed. Consider removing it to keep the codebase clean. If it's needed, resolve the issue and uncomment the code.

apps/system-e2e/src/tests/islandis/application-system/acceptance/parental-leave.spec.ts (2)

275-276: Remove redundant selectText() before fill()

The .fill() method overwrites the content of the input field, making selectText() unnecessary. Simplify the code by removing selectText().

Apply this diff:

-     await phoneNumber.selectText()
      await phoneNumber.fill('6555555')

289-290: Eliminate unnecessary selectText() before fill()

Since .fill() replaces the entire input value, selectText() is redundant. Remove it to streamline the code.

Apply this diff:

-     await paymentBank.selectText()
      await paymentBank.fill('051226054678')
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between db83d3f and c243a39.

📒 Files selected for processing (6)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/parental-leave.spec.ts (10 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1 hunks)
  • libs/application/templates/social-insurance-administration/old-age-pension/src/forms/OldAgePensionForm.ts (1 hunks)
  • libs/application/templates/social-insurance-administration/old-age-pension/src/forms/Prerequisites.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/parental-leave.spec.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/application/templates/social-insurance-administration/old-age-pension/src/forms/OldAgePensionForm.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/old-age-pension/src/forms/Prerequisites.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (11)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts (2)

1-11: LGTM: Imports and function declaration are well-structured

The imports are appropriate for the task, including necessary HTTP methods, response handling, and date manipulation functions. The main function loadParentalLeaveXroadMocks is correctly exported and declared as async, which is suitable for setting up multiple mocks.


41-52: LGTM: Marital status mock is well-structured

The mock setup for fetching marital status from the National Registry is consistent with the previous mock and provides an appropriate response structure. Remember to apply the suggested parameterization of the kennitala here as well if you implement that change.

libs/application/templates/social-insurance-administration/old-age-pension/src/forms/Prerequisites.ts (1)

72-72: LGTM! Consistent with the previous change.

The addition of dataTestId for the half old-age pension option is consistent with the previous change and improves testability.

As mentioned in the previous comment, consider using constants for these test IDs.

libs/application/templates/social-insurance-administration/old-age-pension/src/forms/OldAgePensionForm.ts (1)

295-295: Approved: Added data-test-id for improved testability

The addition of dataTestId: 'personal-allowance-usage' to the paymentInfo.personalAllowanceUsage field is a good practice. It enhances the testability of the component by providing a reliable selector for end-to-end or integration tests.

apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

12-12: Integration of parental leave Xroad mocks is correct

The addition of await loadParentalLeaveXroadMocks() properly incorporates the parental leave mocks into the Xroad setup. This enhances modularity and keeps the setup organized.

apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (1)

185-186: ⚠️ Potential issue

Handle potential invalid month selection

The TODO comment suggests that the month may not be valid. Please implement a check to ensure that the selected month is valid, or adjust the test to handle cases where the month might not be valid.

apps/system-e2e/src/tests/islandis/application-system/acceptance/parental-leave.spec.ts (5)

1-3: Appropriate inclusion of date-fns imports

The addition of addDays and addMonths imports from date-fns is appropriate for date manipulation in tests.


21-27: Approved: Importing environment variables and URLs

Importing BaseAuthority, TestEnvironment, env, getEnvironmentBaseUrl, and urls supports environment-specific configurations, enhancing test flexibility.


86-86: Approved: Using test.beforeAll for setup

Switching to test.beforeAll optimizes the test suite by initializing the context once before all tests, improving efficiency.


90-90: Approved: Setting test phone number

Setting the test phone number to '0103019' is acceptable for testing purposes.


93-94: Verify shared email accounts do not cause test interference

Initializing applicant and employer email accounts in test.beforeAll shares them across all tests. Ensure that test cases do not interfere with each other by modifying the shared email accounts, which could lead to flaky tests.

Copy link

codecov bot commented Oct 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.75%. Comparing base (4309e6f) to head (2bfdec6).
Report is 22 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #16369   +/-   ##
=======================================
  Coverage   36.74%   36.75%           
=======================================
  Files        6804     6804           
  Lines      140882   140902   +20     
  Branches    40124    40137   +13     
=======================================
+ Hits        51765    51786   +21     
+ Misses      89117    89116    -1     
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.44% <ø> (-0.01%) ⬇️
application-template-api-modules 27.96% <ø> (-0.02%) ⬇️
application-ui-shell 21.27% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

see 6 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 4309e6f...2bfdec6. Read the comment docs.

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

🧹 Outside diff range and nitpick comments (6)
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

12-15: Approve centralized mock setup and suggest minor improvement

The refactoring to use loadParentalLeaveXroadMocks and loadSocialInsuranceAdministrationXroadMocks is a significant improvement. It centralizes the mock setup process, enhancing code organization and maintainability.

To further improve code clarity, consider adding a brief comment explaining the purpose of these mock setups:

/* Setup X-Road mocks for different services */
await loadParentalLeaveXroadMocks()
await loadSocialInsuranceAdministrationXroadMocks()

This change aligns with NextJS best practices by improving the structure and readability of the testing framework.

apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (4)

15-37: LGTM: Test configuration is well-structured, with a suggestion for improvement

The test configuration is well-organized and follows Playwright best practices. It properly sets up the application context, manages resources, and isolates the test environment.

Consider defining an interface for the session function parameters to enhance type safety:

interface SessionOptions {
  browser: Browser;
  homeUrl: string;
  phoneNumber: string;
  idsLoginOn: boolean;
}

const applicationContext = await session({
  browser,
  homeUrl,
  phoneNumber: '0103019',
  idsLoginOn: true,
} as SessionOptions)

46-66: LGTM: Application type selection and data provider agreement steps are well-implemented

The test steps for selecting the application type and agreeing to data providers are well-structured and follow a logical flow. The use of expect assertions to verify the visibility of elements is appropriate.

Consider adding assertions to verify the state of the selected options after clicking:

await page.getByTestId('old-age-pension').click()
await expect(page.getByTestId('old-age-pension')).toBeChecked()

await page.getByTestId('agree-to-data-providers').click()
await expect(page.getByTestId('agree-to-data-providers')).toBeChecked()

This ensures that the options are not only clicked but also properly selected.


68-108: LGTM: Pension fund questions and applicant info steps are well-implemented

The test steps for answering pension fund questions and filling in applicant information are well-structured and follow a logical flow. The use of expect assertions to verify the visibility of elements is appropriate.

Consider adding an assertion to verify the phone number input value after filling:

await phoneNumber.fill('6555555')
await expect(phoneNumber).toHaveValue('6555555')

This ensures that the phone number is not only entered but also properly set in the input field.


109-261: LGTM: Comprehensive test steps with suggestions for improvement

The test steps comprehensively cover the entire Old Age Pension application process, including payment information, payment frequency, residence history, period selection, attachments, comments, and submission. The consistent use of expect assertions throughout the process is commendable.

There's a TODO comment regarding file upload functionality:

// TODO: Need to look into this, it may happen that a month is not valid

Would you like assistance in investigating this issue or creating a GitHub issue to track it?

Consider adding an assertion after submitting the application to verify that the submission was successful:

await page
  .getByRole('button', {
    name: label(
      socialInsuranceAdministrationMessage.confirm.submitButton,
    ),
  })
  .click()

// Add this assertion
await expect(page.getByText(/Application submitted successfully/)).toBeVisible({ timeout: 10000 })

This ensures that the application submission process completes successfully.

apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (1)

93-139: Ensure Mock Data Does Not Contain Real Personal Information

The mock data includes personal identifiers like kennitala, names, and addresses. While it's acceptable in a testing environment, please verify that this data does not correspond to real individuals to prevent any unintended exposure of personal information.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c243a39 and b10d101.

📒 Files selected for processing (4)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/parentalLeave.mock.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (4)
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

3-7: Approve new imports and consider using module aliases

The addition of new import statements for loadParentalLeaveXroadMocks and loadSocialInsuranceAdministrationXroadMocks is a good step towards centralizing mock setup. This change improves the overall structure of the testing framework.

To further improve code readability, consider implementing module aliases as suggested in a previous review. This would simplify the deeply nested relative import paths, making the code easier to maintain.

For example, you could use:

import { Base } from '@infra/dsl/xroad'
import { env } from '@support/urls'
import { resetMocks, wildcard } from '@support/wire-mocks'
import { loadParentalLeaveXroadMocks } from '@mocks/parentalLeave.mock'
import { loadSocialInsuranceAdministrationXroadMocks } from '@mocks/socialInsuranceAdministration.mock'

This requires configuring path mappings in your tsconfig.json file.

apps/system-e2e/src/tests/islandis/application-system/acceptance/old-age-pension.spec.ts (3)

1-14: LGTM: Imports and initial setup are well-structured

The import statements and initial setup are well-organized and include all necessary modules for the end-to-end test. The homeUrl constant is correctly defined for the Old Age Pension application.


39-45: LGTM: Test description and initial setup are clear and concise

The test suite description for "Old Age Pension" is well-defined. The use of the helpers function to set up reusable test actions, such as proceed(), is a good practice for maintaining clean and DRY test code.


262-280: LGTM: Conclusion screen verification is well-implemented

The final test step appropriately checks for the visibility of the conclusion screen header, ensuring that the application process has completed successfully. The use of the expect assertion to verify the presence of the header is correct and follows best practices.

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

🧹 Outside diff range and nitpick comments (6)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (3)

6-37: LGTM: Currency mock setup is comprehensive.

The mock for '/api/protected/v1/General/currencies' is well-configured and returns a substantial list of currency codes.

Consider adding a comment explaining the purpose of this mock and whether the currency list is exhaustive or if it should be updated periodically.


53-63: LGTM: Old age pension eligibility mock is well-structured.

The mock for '/api/protected/v1/Applicant/oldagepension/eligible' provides a clear structure for eligibility checks.

Consider adding variations of this mock (e.g., not eligible scenarios) to test different use cases. This could be achieved by parameterizing the mock setup or creating separate mock functions for different scenarios.


1-74: Overall, excellent mock setup with room for minor enhancements.

The socialInsuranceAdministration.mock.ts file is well-structured and provides comprehensive mock setups for various Social Insurance Administration API endpoints. The mocks cover currencies, applicant details, eligibility checks, and application submissions, which should facilitate thorough e2e testing.

To further improve the file:

  1. Consider adding JSDoc comments to the main function and each mock setup to explain their purposes and any assumptions made.
  2. Explore options to make the mock setups more flexible, such as parameterizing the responses or creating separate functions for different scenarios (e.g., eligible vs. non-eligible applicants).
  3. If these mocks are part of a larger testing strategy, consider adding a comment at the file level explaining how this file fits into the overall e2e testing approach.

These enhancements would improve maintainability and make the file even more valuable for future development and testing efforts.

apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/nationalRegistry.mocks.ts (3)

5-85: Function structure is well-organized, but could benefit from minor readability improvements.

The loadNationalRegistryXroadMocks function is well-structured and makes good use of async/await. The mock data is comprehensive and realistic. However, consider adding comments or separating the different mock setups (e.g., personal info, marital status, citizenship) into smaller functions for improved readability.

Consider refactoring the function to improve readability:

export const loadNationalRegistryXroadMocks = async () => {
  await setupPersonalInfoMock('0101303019', 'Gervimaður Afríka');
  await setupMaritalStatusMock('0101303019');
  await setupCitizenshipMock('0101303019');
  await setupResidenceHistoryMock('0101303019');
  // ... other mock setups
}

async function setupPersonalInfoMock(kennitala: string, name: string) {
  await addXroadMock({
    // ... existing configuration
  });
}

// Similar functions for other mock setups

87-149: Consistent structure for mock data, but consider centralizing data management.

The mock data for the second individual is well-structured and consistent with the first. It provides a good variety of test scenarios. However, to improve maintainability and reduce duplication, consider centralizing the mock data in a separate file.

Consider creating a separate file for mock data:

// mockData.ts
export const individualsMockData = {
  '0101303019': {
    personalInfo: { /* ... */ },
    maritalStatus: { /* ... */ },
    // ... other data
  },
  '0101307789': {
    personalInfo: { /* ... */ },
    maritalStatus: { /* ... */ },
    // ... other data
  },
};

// In nationalRegistry.mocks.ts
import { individualsMockData } from './mockData';

// Use the imported data in your mock setups

This approach would make it easier to manage and update mock data across different test scenarios.


151-162: General data mock is good, but consider improving extensibility.

The mock for marital status codes is well-structured and consistent with other mocks. However, to improve extensibility and cover more scenarios, consider setting up mocks for multiple marital status codes.

Enhance the marital status code mocks:

const maritalStatusCodes = [
  { kodi: '1', lysing: 'Ógiftur' },
  { kodi: '2', lysing: 'Giftur' },
  // Add more status codes as needed
];

for (const status of maritalStatusCodes) {
  await addXroadMock({
    config: NationalRegistry,
    prefix: 'XROAD_NATIONAL_REGISTRY_SERVICE_PATH',
    apiPath: `/api/v1/lyklar/hjuskaparkodar/1/${status.kodi}`,
    prefixType: 'only-base-path',
    response: new Response().withJSONBody(status),
  });
}

This approach allows for easy addition of new marital status codes and ensures comprehensive test coverage.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b10d101 and 2bfdec6.

📒 Files selected for processing (3)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/nationalRegistry.mocks.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (1 hunks)
  • apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/nationalRegistry.mocks.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (9)
apps/system-e2e/src/tests/islandis/application-system/acceptance/setup-xroad.mocks.ts (3)

6-8: LGTM: New imports are well-structured and consistent

The new imports for mock loading functions are clear, descriptive, and align well with the changes in the setupXroadMocks function. This structure follows good practices for organizing test files in NextJS projects.

Regarding the previous suggestion about using module aliases:

The recommendation to use module aliases for cleaner import paths, especially for deeply nested imports (lines 1-5), is still valid and would improve code readability. Consider implementing path mappings in your tsconfig.json as suggested in the previous review.


13-17: Great refactoring: Improved modularity and maintainability

The changes to the setupXroadMocks function significantly improve the code structure:

  1. Enhanced modularity: Mock setups are now separated into individual functions, making the code more organized and easier to maintain.
  2. Improved readability: The main function is now more concise and easier to understand at a glance.
  3. Correct use of async/await: The new function calls properly use the async/await pattern.

These changes align well with NextJS best practices for structuring test setups and will make future modifications and additions to the mocks easier to manage.


Line range hint 1-31: Excellent adherence to NextJS best practices and improved test structure

The changes in this file demonstrate a strong commitment to NextJS best practices and improved test structure:

  1. Modular approach: Breaking down mock setups into separate functions enhances reusability and maintainability.
  2. TypeScript usage: The code leverages TypeScript for improved type safety and developer experience.
  3. Async/await patterns: Proper use of async/await ensures efficient handling of asynchronous operations.
  4. Clear file organization: The file structure follows NextJS conventions for e2e test setups.

These improvements contribute to a more robust and maintainable test suite, which is crucial for ensuring the reliability of the application system.

apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/socialInsuranceAdministration.mock.ts (4)

1-3: LGTM: Import statements are appropriate and concise.

The import statements are well-organized and relevant to the file's purpose. They include necessary components from external libraries and internal modules required for setting up the mock responses.


5-5: LGTM: Function structure is well-defined and extensible.

The loadSocialInsuranceAdministrationXroadMocks function is appropriately exported and async. Its structure allows for easy addition of more mock setups in the future.


38-52: LGTM: Applicant mock setup provides necessary details.

The mock for '/api/protected/v1/Applicant' is well-structured and includes essential applicant information.

Is the null phone number intentional? If it's meant to represent a possible real-world scenario where the phone number is not provided, consider adding a comment to clarify this intention.


64-73: LGTM: Old age pension application mock is correctly configured.

The mock for '/api/protected/v1/Application/oldagepension' is well-structured and correctly set up for POST requests. It appropriately simulates the application submission process by returning an application line ID.

apps/system-e2e/src/tests/islandis/application-system/acceptance/mocks/nationalRegistry.mocks.ts (2)

1-3: Imports look good and follow best practices.

The imports are appropriate for the file's purpose, using relative paths for project-specific imports and a named import for the external library. This follows NextJS best practices and makes good use of TypeScript.


1-162: Overall, well-structured mock setup with room for minor improvements.

This file successfully sets up comprehensive mock data for the National Registry service, adhering to NextJS best practices and making good use of TypeScript. The mock scenarios cover a wide range of data types and situations, which will be valuable for thorough e2e testing.

To further improve the file:

  1. Consider breaking down the large loadNationalRegistryXroadMocks function into smaller, more focused functions.
  2. Centralize mock data in a separate file for easier management and updates.
  3. Enhance the extensibility of general data mocks, such as marital status codes.

These improvements will enhance maintainability and scalability as the test suite grows.

@veronikasif veronikasif deleted the feat/old-age-pension-e2e branch October 15, 2024 12:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants