Skip to content

feat: add solution for day 26 #295

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

hunghoang3110
Copy link
Contributor

@hunghoang3110 hunghoang3110 commented Feb 26, 2025

Summary by CodeRabbit

  • Tests
    • Implemented new automated checks to verify that items are reliably added to the in-game market cart.
    • Confirms correct feedback is provided during the shopping process, even when navigating through multiple pages.

Copy link
Contributor

coderabbitai bot commented Feb 26, 2025

Walkthrough

A new test file has been added to verify the functionality of adding items in a market simulation game using Playwright. The test validates the market page by confirming the title, iterates through table rows to add items with proper error handling for null values and pagination, and finally verifies a successful operation via a dialog handler. A helper function, getCellText, is introduced to extract text from table cells.

Changes

File Change Summary
daily-challenges/.../hunghoang3110.spec.ts Added a new test file to simulate item addition in a market game. Includes steps to navigate, verify page title, iterate table rows, handle pagination and errors, and verify success via a dialog. Also introduces the helper function getCellText.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Runner
    participant Market as Market Page
    participant Table as Food Items Table
    participant Dialog as Dialog Handler

    Test->>Market: Navigate to market page
    Market-->>Test: Display page with title and items table
    Test->>Table: Retrieve list of food items
    alt Item visible
        Table-->>Test: Return item details
        Test->>Market: Add item to cart
    else Item not visible
        Test->>Market: Navigate to next page (max attempts)
    end
    Test->>Dialog: Click result check button
    Dialog-->>Test: Show success message
Loading

Suggested reviewers

  • minhphong306

Poem

I'm a bunny on a code-bound spree,
Hoping through tests so merrily.
With each item added, my heart leaps high,
Pagination and errors, now they fly by.
Hoppity cheers for changes made—let's code and hop sky-high!

Tip

CodeRabbit's docstrings feature is now available as part of our Pro Plan! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1962b78 and a87fadf.

📒 Files selected for processing (1)
  • daily-challenges/2024-10/26/hunghoang3110.spec.ts (1 hunks)
🔇 Additional comments (2)
daily-challenges/2024-10/26/hunghoang3110.spec.ts (2)

6-9: Good use of step organization and page verification.

The navigation step is well-structured with appropriate page verification. Using test.step improves test readability and debugging.


71-74: Good helper function implementation.

The getCellText helper function is well-typed and properly encapsulates the cell text extraction logic.

Comment on lines +60 to +68
await test.step('Check the result', async () => {
// Set up dialog handler first
page.on('dialog', dialog => {
expect(dialog.message()).toBe('Bạn đã đi chợ chính xác!');
dialog.accept();
});
await page.getByRole('button', {name: 'Kiểm tra kết quả'})
.click();
})
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

Verify dialog appears with a timeout.

The code sets up a dialog handler but doesn't verify the dialog actually appears. If the dialog never shows up, the test will pass silently.

await test.step('Check the result', async () => {
    // Set up dialog handler first
+   let dialogShown = false;
    page.on('dialog', dialog => {
        expect(dialog.message()).toBe('Bạn đã đi chợ chính xác!');
+       dialogShown = true;
        dialog.accept();
    });
    await page.getByRole('button', {name: 'Kiểm tra kết quả'})
        .click();
+   
+   // Wait for dialog to appear with timeout
+   await expect.poll(() => dialogShown, {
+       message: 'Dialog did not appear',
+       timeout: 5000
+   }).toBe(true);
})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await test.step('Check the result', async () => {
// Set up dialog handler first
page.on('dialog', dialog => {
expect(dialog.message()).toBe('Bạn đã đi chợ chính xác!');
dialog.accept();
});
await page.getByRole('button', {name: 'Kiểm tra kết quả'})
.click();
})
await test.step('Check the result', async () => {
// Set up dialog handler first
let dialogShown = false;
page.on('dialog', dialog => {
expect(dialog.message()).toBe('Bạn đã đi chợ chính xác!');
dialogShown = true;
dialog.accept();
});
await page.getByRole('button', {name: 'Kiểm tra kết quả'})
.click();
// Wait for dialog to appear with timeout
await expect.poll(() => dialogShown, {
message: 'Dialog did not appear',
timeout: 5000
}).toBe(true);
})

Comment on lines +36 to +56
for (let i = 1; i <= maxAttempts; i++) {
const isVisible = await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood, {exact: true}) })
.isVisible();
if (isVisible) {
for (let index = 0; index < Number(quantity); index++) {
await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood) })
.getByRole('button', { name: '+' })
.click();
}
break;
} else {
// Move to the next page if the item cannot be found in the current page
console.log(`Not found on attempt ${i + 1}`);
await page.getByRole('button', { name: 'Trang sau' })
.click();

}
}
})
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

Add handling for items not found after maximum attempts.

The code doesn't handle the case where an item isn't found after the maximum number of attempts. This could lead to silent failures.

for (let i = 1; i <= maxAttempts; i++) {
    const isVisible = await page.locator('.product-item')
        .filter({ has: page.getByText(nameOfFood, {exact: true}) })
        .isVisible();
    if (isVisible) {
        for (let index = 0; index < Number(quantity); index++) {
            await page.locator('.product-item')
                .filter({ has: page.getByText(nameOfFood) })
                .getByRole('button', { name: '+' })
                .click();
        }
        break;
    } else {
        // Move to the next page if the item cannot be found in the current page
        console.log(`Not found on attempt ${i + 1}`);
        await page.getByRole('button', { name: 'Trang sau' })
            .click();

    }
+   // Add handling for when item is not found after max attempts
+   if (i === maxAttempts) {
+       console.error(`Failed to find item "${nameOfFood}" after ${maxAttempts} attempts`);
+       // Consider whether to fail the test or continue with other items
+       // throw new Error(`Item "${nameOfFood}" not found after ${maxAttempts} page attempts`);
+   }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for (let i = 1; i <= maxAttempts; i++) {
const isVisible = await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood, {exact: true}) })
.isVisible();
if (isVisible) {
for (let index = 0; index < Number(quantity); index++) {
await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood) })
.getByRole('button', { name: '+' })
.click();
}
break;
} else {
// Move to the next page if the item cannot be found in the current page
console.log(`Not found on attempt ${i + 1}`);
await page.getByRole('button', { name: 'Trang sau' })
.click();
}
}
})
for (let i = 1; i <= maxAttempts; i++) {
const isVisible = await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood, {exact: true}) })
.isVisible();
if (isVisible) {
for (let index = 0; index < Number(quantity); index++) {
await page.locator('.product-item')
.filter({ has: page.getByText(nameOfFood) })
.getByRole('button', { name: '+' })
.click();
}
break;
} else {
// Move to the next page if the item cannot be found in the current page
console.log(`Not found on attempt ${i + 1}`);
await page.getByRole('button', { name: 'Trang sau' })
.click();
}
// Add handling for when item is not found after max attempts
if (i === maxAttempts) {
console.error(`Failed to find item "${nameOfFood}" after ${maxAttempts} attempts`);
// Consider whether to fail the test or continue with other items
// throw new Error(`Item "${nameOfFood}" not found after ${maxAttempts} page attempts`);
}
}
})

Comment on lines +17 to +34
const numberOfRows = await listMarket.getByRole('row').count() - 1;
for (let index = 1; index <= numberOfRows; index++) {
const orderRow = listMarket.getByRole('row').nth(index);
const nameOfFood = await getCellText(orderRow, 0);
const quantity = await getCellText(orderRow, 1);
if (nameOfFood === null || quantity === null) {
throw new Error('Cell text is null');
}
let currentPage = await page.locator('#page-number').textContent();
if (currentPage === null) {
throw new Error('Cell text is null');
}
// First, go back to the first page
while (Number(currentPage) > 1) {
await page.getByRole('button', { name: 'Trang trước' })
.click();
currentPage = await page.locator('#page-number').textContent();
}
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

Improve navigation efficiency by not resetting to page 1 for every item.

The current approach resets to page 1 for each food item, which is inefficient. Consider processing all items on the current page before moving to the next page.

-const numberOfRows = await listMarket.getByRole('row').count() - 1;
-for (let index = 1; index <= numberOfRows; index++) {
-    const orderRow = listMarket.getByRole('row').nth(index);
-    const nameOfFood = await getCellText(orderRow, 0);
-    const quantity = await getCellText(orderRow, 1);
-    if (nameOfFood === null || quantity === null) {
-        throw new Error('Cell text is null');
-    }
-    let currentPage = await page.locator('#page-number').textContent();
-    if (currentPage === null) {
-        throw new Error('Cell text is null');
-    }
-    // First, go back to the first page
-    while (Number(currentPage) > 1) {
-        await page.getByRole('button', { name: 'Trang trước' })
-            .click();
-        currentPage = await page.locator('#page-number').textContent();
-    }
+// Extract all food items and quantities from the table
+const foodItems = [];
+const numberOfRows = await listMarket.getByRole('row').count() - 1;
+for (let index = 1; index <= numberOfRows; index++) {
+    const orderRow = listMarket.getByRole('row').nth(index);
+    const nameOfFood = await getCellText(orderRow, 0);
+    const quantity = await getCellText(orderRow, 1);
+    if (nameOfFood === null || quantity === null) {
+        throw new Error('Cell text is null');
+    }
+    foodItems.push({ name: nameOfFood, quantity: Number(quantity) });
+}
+
+// Reset to page 1 once before processing all items
+let currentPage = await page.locator('#page-number').textContent();
+if (currentPage === null) {
+    throw new Error('Page number is null');
+}
+
+while (Number(currentPage) > 1) {
+    await page.getByRole('button', { name: 'Trang trước' })
+        .click();
+    currentPage = await page.locator('#page-number').textContent();
+}
+
+// Now process all food items
+for (const { name: nameOfFood, quantity } of foodItems) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const numberOfRows = await listMarket.getByRole('row').count() - 1;
for (let index = 1; index <= numberOfRows; index++) {
const orderRow = listMarket.getByRole('row').nth(index);
const nameOfFood = await getCellText(orderRow, 0);
const quantity = await getCellText(orderRow, 1);
if (nameOfFood === null || quantity === null) {
throw new Error('Cell text is null');
}
let currentPage = await page.locator('#page-number').textContent();
if (currentPage === null) {
throw new Error('Cell text is null');
}
// First, go back to the first page
while (Number(currentPage) > 1) {
await page.getByRole('button', { name: 'Trang trước' })
.click();
currentPage = await page.locator('#page-number').textContent();
}
// Extract all food items and quantities from the table
const foodItems = [];
const numberOfRows = await listMarket.getByRole('row').count() - 1;
for (let index = 1; index <= numberOfRows; index++) {
const orderRow = listMarket.getByRole('row').nth(index);
const nameOfFood = await getCellText(orderRow, 0);
const quantity = await getCellText(orderRow, 1);
if (nameOfFood === null || quantity === null) {
throw new Error('Cell text is null');
}
foodItems.push({ name: nameOfFood, quantity: Number(quantity) });
}
// Reset to page 1 once before processing all items
let currentPage = await page.locator('#page-number').textContent();
if (currentPage === null) {
throw new Error('Page number is null');
}
while (Number(currentPage) > 1) {
await page.getByRole('button', { name: 'Trang trước' })
.click();
currentPage = await page.locator('#page-number').textContent();
}
// Now process all food items
for (const { name: nameOfFood, quantity } of foodItems) {

Comment on lines +3 to +5
test('Check the Add item function', async ({ page }) => {
const maxAttempts = 3;

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM. Consider defining constants closer to their usage.

The test structure is well-organized with a clear title. The maxAttempts constant is defined early but only used much later at line 36, making it harder to understand the connection.

-const maxAttempts = 3;

+// Other code...
+
+await test.step('Add the quantity of item', async () => {
+    const maxAttempts = 3;

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

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.

1 participant