How to Test Shopping Cart Quantity and Price Calculations Using Playwright

 

Imagine a customer visits an online shopping website and adds three mobile phones to the shopping cart.

Each mobile phone costs ₹10,000.

The expected product subtotal is ₹30,000.

However, the shopping website displays ₹20,000 instead of ₹30,000.

The customer may become confused and lose trust in the website.

Now imagine another situation.

A customer applies a 10% discount coupon, but the website calculates the discount incorrectly.

These are examples of shopping cart calculation problems.

Shopping cart testing helps QA engineers identify incorrect quantities, product prices, discounts, taxes, shipping charges and total amounts before customers complete their purchases.

Playwright can automate these scenarios and verify whether an e-commerce website calculates shopping cart values correctly.

In this guide, you will learn how to test shopping cart quantity and price calculations using Playwright and JavaScript.

What Is Shopping Cart Testing?

Shopping cart testing is the process of checking whether an online shopping website correctly manages selected products, quantities and prices.

A shopping cart works like a basket in a physical supermarket.

Customers select products, change quantities, remove items and review the total amount before purchasing.

A shopping cart generally contains:

  • Product name.

  • Product image.

  • Product price.

  • Product quantity.

  • Product subtotal.

  • Discount amount.

  • Tax amount.

  • Shipping charges.

  • Final payable amount.

QA engineers must verify that these values are accurate whenever customers make changes.

Why Is Shopping Cart Calculation Testing Important?

Incorrect cart calculations can create serious problems for e-commerce businesses.

Consider these situations:

Situation 1: Incorrect Quantity

A customer selects five products, but the shopping cart displays only four.

Situation 2: Incorrect Subtotal

A product costs ₹500, and the customer selects three units.

The correct subtotal is ₹1,500.

But the website displays ₹1,000.

Situation 3: Incorrect Discount

The website offers a 20% discount, but applies only 10%.

Situation 4: Incorrect Tax

The website calculates tax using the wrong amount.

Situation 5: Incorrect Final Total

The product price, discount, tax and shipping charges are not added correctly.

All these situations can affect customer trust, order accuracy and business revenue.

Understanding Shopping Cart Price Calculations

Before creating automation scripts, understand how shopping cart calculations work.

Let's use a simple example.

A customer purchases:

Product

Price

Quantity

Subtotal

Keyboard

₹1,000

2

₹2,000

Mouse

₹500

1

₹500

Headphones

₹2,000

1

₹2,000

Total



₹4,500

The product subtotal is calculated by multiplying each product price by its quantity and adding all product subtotals.

Formula:

Product Subtotal = Product Price × Quantity

Cart Subtotal = Sum of All Product Subtotals

For the example:

₹2,000 + ₹500 + ₹2,000 = ₹4,500.

Now suppose the customer receives a ₹500 discount.

Discounted Amount = ₹4,500 − ₹500 = ₹4,000.

If shipping costs ₹100 and tax is ₹200:

Final Total = ₹4,000 + ₹100 + ₹200.

Final Payable Amount = ₹4,300.

These are simplified examples. Actual tax, discount and shipping rules depend on the business, jurisdiction and application requirements.

Important Shopping Cart Test Scenarios

A QA engineer should test more than just adding products to a cart.

Here are the most important scenarios.

1. Add a Single Product

Test whether a customer can add one product to the shopping cart.

Verify:

  • Product name.

  • Product price.

  • Product quantity.

  • Product subtotal.

Expected result:

The cart should contain the selected product with quantity one and the correct price.

2. Add Multiple Products

Customers may purchase different products in one order.

For example:

  • One keyboard.

  • Two mice.

  • One monitor.

Verify that all products appear correctly.

Expected result:

Every product should display the correct quantity and subtotal.

3. Increase Product Quantity

Suppose a customer adds one keyboard costing ₹1,000.

The customer changes the quantity from one to three.

Expected calculation:

₹1,000 × 3 = ₹3,000.

Verify that the website updates the subtotal to ₹3,000.

4. Decrease Product Quantity

Suppose the cart contains four products.

The customer reduces the quantity to two.

The cart should immediately reflect the new quantity and subtotal according to the application's update behavior.

5. Remove a Product

Verify whether customers can remove products from their shopping cart.

Expected result:

The selected product should disappear and the cart total should be recalculated.

6. Test Minimum Quantity

Some products require a minimum purchase quantity.

For example, a customer may need to purchase at least two units.

Verify whether the application prevents invalid quantities.

7. Test Maximum Quantity

Some products have purchase limits.

For example, a customer may purchase a maximum of ten units.

Verify whether the website prevents quantities above the allowed limit.

8. Test Out-of-Stock Products

A product may become unavailable after a customer adds it to the cart.

Verify whether the website updates availability and prevents an invalid purchase.

9. Test Discount Coupons

Verify:

  • Valid coupons.

  • Expired coupons.

  • Invalid coupons.

  • Minimum purchase requirements.

  • Maximum discount limits.

  • Coupon removal.

  • Multiple coupon restrictions.

10. Test Tax and Shipping Calculations

Verify whether tax and shipping charges change according to the applicable business rules.

For example, shipping may be free for orders above a specific amount.

The automation should verify the correct behavior for orders below and above that threshold.

How to Automate Shopping Cart Testing Using Playwright

Now let's create practical automation examples.

We will use:

  • JavaScript.

  • Playwright Test.

  • VS Code.

  • A demo e-commerce application.

Step 1: Install Playwright

Open your terminal and execute:

npm init playwright@latest

Choose JavaScript when prompted.

After installation, create a test file:

shopping-cart.spec.js

Step 2: Test Adding a Product to the Cart

The following example verifies whether a product is added successfully.

const { test, expect } = require('@playwright/test');


test('Verify product is added to cart', async ({ page }) => {


    await page.goto('https://your-demo-store.com');


    await page.getByRole('button', {

        name: 'Add to Cart'

    }).click();


    await page.getByRole('link', {

        name: 'Shopping Cart'

    }).click();


    await expect(

        page.getByText('Wireless Mouse')

    ).toBeVisible();


});

This test:

  1. Opens the shopping website.

  2. Adds a product.

  3. Opens the shopping cart.

  4. Checks whether the product appears.

Replace the example website and locators with your application's actual values.

Step 3: Test Product Quantity

Now let's test whether changing the product quantity updates the cart.

test('Verify shopping cart quantity', async ({ page }) => {


    await page.goto('https://your-demo-store.com/cart');


    const quantity = page.getByLabel('Quantity');


    await quantity.fill('3');


    await expect(quantity).toHaveValue('3');


});

This example checks whether the quantity field accepts the new value.

However, checking the field alone is not enough.

You must also verify that the application updates the subtotal correctly.

Step 4: Test Product Subtotal Calculation

Let's assume:

Product price = ₹1,000

Quantity = 3

Expected subtotal = ₹3,000.

test('Verify product subtotal calculation', async ({ page }) => {


    await page.goto('https://your-demo-store.com/cart');


    const quantity = page.getByLabel('Quantity');


    await quantity.fill('3');


    await page.getByRole('button', {

        name: 'Update Cart'

    }).click();


    await expect(

        page.getByTestId('product-subtotal')

    ).toHaveText('₹3,000');


});

The data-testid attribute should exist in your application.

For example:

<div data-testid="product-subtotal">

    ₹3,000

</div>

Using a stable test ID can make automation easier to maintain.

Step 5: Test Cart Total Using JavaScript

Let's create a simple calculation example.

const productPrice = 1000;


const quantity = 3;


const expectedSubtotal = productPrice * quantity;


console.log(expectedSubtotal);

Output:

3000

Now we can compare this expected value with the amount displayed by the website.

test('Verify calculated cart subtotal', async ({ page }) => {


    await page.goto('https://your-demo-store.com/cart');


    const productPrice = 1000;


    const quantity = 3;


    const expectedSubtotal = productPrice * quantity;


    const quantityField = page.getByLabel('Quantity');


    await quantityField.fill(String(quantity));


    await page.getByRole('button', {

        name: 'Update Cart'

    }).click();


    const actualText = await page

        .getByTestId('product-subtotal')

        .innerText();


    const actualSubtotal = Number(

        actualText.replace(/[₹,\s]/g, '')

    );


    expect(actualSubtotal).toBe(expectedSubtotal);


});

This test compares the expected subtotal with the displayed subtotal.

For real applications, use a proper currency parsing method if the interface displays decimal values, currency codes or locale-specific formats.

Also, the calculation rules should come from the application's approved business requirements rather than assumptions made inside the test.

How to Test Discount Calculations

Discounts are common in e-commerce applications.

For example:

Original product price = ₹2,000.

Discount = 10%.

Expected discount = ₹200.

Discounted price = ₹1,800.

The formula is:

Discount Amount = Original Price × Discount Percentage / 100.

Let's automate this calculation.

test('Verify discount calculation', async ({ page }) => {


    await page.goto('https://your-demo-store.com/cart');


    const originalPrice = 2000;


    const discountPercentage = 10;


    const expectedDiscount =

        originalPrice * discountPercentage / 100;


    const expectedPrice =

        originalPrice - expectedDiscount;


    await page.getByLabel('Coupon Code').fill('SAVE10');


    await page.getByRole('button', {

        name: 'Apply Coupon'

    }).click();


    await expect(

        page.getByTestId('discount-amount')

    ).toHaveText('₹200');


    await expect(

        page.getByTestId('final-price')

    ).toHaveText('₹1,800');


});

This example assumes the application has a coupon named SAVE10.

In a real application, verify that the coupon is valid for the selected products and that the discount rules are correctly applied.

How to Test Tax Calculations

Tax calculations can be different depending on the product, location and business rules.

Consider this simplified example:

Product subtotal = ₹2,000.

Tax rate = 10%.

Expected tax = ₹200.

Final amount before shipping = ₹2,200.

JavaScript calculation:

const subtotal = 2000;


const taxRate = 10;


const taxAmount = subtotal * taxRate / 100;


const total = subtotal + taxAmount;


console.log(taxAmount);


console.log(total);

Expected output:

200

2200

For real applications, tax may be calculated at the line-item level, after discounts, or according to specific regional rules.

The test must follow the actual tax requirements.

How to Test Complete Shopping Cart Calculations

Now let's combine product price, quantity, discount, tax and shipping.

Example:

Calculation

Amount

Product price

₹1,000

Quantity

3

Subtotal

₹3,000

Discount

₹300

Tax

₹270

Shipping

₹100

Final total

₹3,070

Calculation:

Product Subtotal = ₹1,000 × 3 = ₹3,000.

Discounted Subtotal = ₹3,000 − ₹300 = ₹2,700.

Tax = ₹270.

Shipping = ₹100.

Final Total = ₹2,700 + ₹270 + ₹100 = ₹3,070.

Example JavaScript:

const productPrice = 1000;


const quantity = 3;


const discount = 300;


const tax = 270;


const shipping = 100;


const subtotal = productPrice * quantity;


const finalTotal =

    subtotal - discount + tax + shipping;


console.log(finalTotal);

Expected output:

3070

This is a simplified calculation model. Always use the application's actual pricing and tax rules when writing assertions.

Important Edge Cases in Shopping Cart Testing

Edge cases are unusual situations that may reveal hidden application problems.

QA engineers should test these situations before releasing an e-commerce website.

1. Zero Quantity

What happens when a customer enters zero?

Expected result:

The application should follow its defined business rule, such as removing the item or displaying a validation message.

2. Negative Quantity

What happens when a customer enters -2?

Expected result:

The application should reject the invalid quantity.

3. Very Large Quantity

What happens when a customer enters 100000?

Expected result:

The application should enforce purchase limits and prevent invalid calculations.

4. Decimal Quantity

What happens when a customer enters 2.5?

For products sold as whole units, decimal quantities should be rejected.

For products sold by weight or length, decimal quantities may be valid.

The test must follow product-specific requirements.

5. Price Changes

Imagine a product costs ₹1,000 when added to the cart.

Later, its price changes to ₹1,200.

Verify how the application handles this situation.

The website should follow its documented pricing policy and clearly communicate any price changes.

6. Out-of-Stock Products

Verify that the cart does not allow customers to purchase unavailable products.

7. Multiple Discount Codes

Check whether the website allows multiple coupons or only one coupon per order.

8. Cart Persistence

Close the browser and reopen the website.

Check whether the cart remains available according to the application's login and session rules.

How to Organize Shopping Cart Automation Tests

For a professional automation framework, avoid placing every test inside one large file.

Organize tests according to functionality.

Example:

ecommerce-framework/

│

├── tests/

│   ├── product.spec.js

│   ├── shopping-cart.spec.js

│   ├── pricing.spec.js

│   ├── discount.spec.js

│   └── checkout.spec.js

│

├── pages/

│   ├── HomePage.js

│   ├── ProductPage.js

│   ├── CartPage.js

│   └── CheckoutPage.js

│

├── test-data/

│   └── products.json

│

├── playwright.config.js

│

└── package.json

This structure separates test cases, reusable page methods and test data.

It becomes easier to maintain when the application grows.

Best Practices for Shopping Cart Automation

  1. Use stable and meaningful locators.

  2. Verify both product quantity and calculated totals.

  3. Test positive and negative scenarios.

  4. Use reusable functions for repeated actions.

  5. Keep test data separate from test scripts.

  6. Test discount and coupon boundaries.

  7. Validate backend cart values where appropriate.

  8. Use isolated test data.

  9. Avoid fixed waits whenever possible.

  10. Test supported browsers and mobile layouts.

  11. Handle currency and decimal precision correctly.

  12. Verify that displayed totals match the application's authoritative pricing rules.

Shopping Cart Testing Checklist

Test Area

What to Verify

Product Addition

Product added successfully

Product Removal

Product removed correctly

Quantity

Quantity increases and decreases

Minimum Quantity

Minimum purchase rules

Maximum Quantity

Purchase limits

Subtotal

Correct product calculations

Discount

Correct coupon application

Tax

Correct tax rules

Shipping

Correct delivery charges

Final Total

Accurate payable amount

Stock

Product availability

Cart Persistence

Cart session behavior

Price Updates

Updated price handling

Invalid Inputs

Zero, negative and invalid quantities

Frequently Asked Questions

What is shopping cart testing in software testing?

Shopping cart testing verifies whether an e-commerce website correctly manages selected products, quantities, product prices, discounts, taxes, shipping charges and final order totals.

Can Playwright test shopping cart calculations?

Yes. Playwright can interact with quantity fields, update cart values, read displayed prices and compare them with expected calculations using JavaScript assertions.

How do you test product quantity in Playwright?

Use a locator to identify the quantity field, update its value and verify the new value and corresponding subtotal.

How do you test discount coupons using Playwright?

Enter a valid or invalid coupon code, apply it and verify the discount amount, final total and appropriate validation messages.

How do you test incorrect price calculations?

Calculate the expected amount using the application's business rules, read the displayed amount and compare both values using Playwright assertions.

Why is cart testing important before an e-commerce release?

Cart testing helps identify incorrect product quantities, pricing errors, discount problems and incorrect order totals before customers make purchases.

Conclusion

Shopping cart testing is an important part of e-commerce application testing.

A small calculation error can affect the customer's final payment and create problems for the business.

Playwright helps QA engineers automate product selection, quantity changes, price calculations, discount validation, tax verification and cart updates.

By combining browser automation with accurate business-rule validation, testers can identify pricing problems before they reach customers.

Practise these scenarios with a demo shopping application and gradually build a reusable Playwright automation framework.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide