Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 35 ยท Projects

Project: Shopping Cart Checkout

Automate an end-to-end shopping flow: add items, verify totals, choose shipping from a dropdown, wait for an async checkout and assert the order confirmation.

A shopping cart is where UI testing gets interesting. There are many small steps, numbers that must add up, a dropdown that changes the price, and a final action that takes a moment to finish. A test that clicks through it must wait at the right places and assert the right things. In this project you will plan and write an end-to-end checkout test, and learn how to keep it fast and stable.

As in the other projects, the real Selenium code (Python) is read-only, because this site cannot launch a browser. A stand-in shop runs in the page so you can see the logic: money math in cents, a shipping choice, and a checkout that completes after a delay. The ideas carry over to the real thing one to one.

One flow, five checkpoints

Add items The cart count changes.
Check totals Subtotal, shipping, tax, total.
Pick shipping A dropdown changes the price.
Place order The result arrives later.

Assert at each checkpoint, wait only where the page is asynchronous.

1 / 2

Plan the flow

An end-to-end test follows one user journey from start to finish. For the cart, the journey is:

  1. Open the shop.
  2. Add two mugs and one poster.
  3. Open the cart and check the count and the totals.
  4. Choose express shipping and check the total again.
  5. Place the order and wait for the confirmation.
  6. Check the order number is shown.

Resist the urge to put every check into this one test. A single long journey is valuable as a smoke test of the whole path, but small focused tests (for example "tax is rounded correctly" or "quantity limit is enforced") find problems faster and fail with clearer messages. Calculations in particular are better checked below the UI, in unit tests, because they do not need a browser. The UI test then only needs to confirm that the page shows the number the code computed.

Money: compare exact values

Prices are the classic source of silly bugs. Floating-point numbers cannot represent most decimal amounts exactly, so many shops store prices in cents as integers. In your tests, do the same:

  • Parse the text you read from the page ("$53.04") into cents before comparing, or compare normalized strings.
  • Never compare floats with ==. In Python use decimal.Decimal or integers.
  • Always check the rounding rule. If tax is 8 percent of 44.48, the exact tax is 3.5584, and the shop must round it to 3.56. A test that only uses round numbers will never notice a rounding bug.

Here is the cart logic of the stand-in shop in isolation, with a few checks. It is deliberately UI-free so you can see the business rules the end-to-end test will rely on: tax of 8 percent rounded to the nearest cent, standard shipping of $5.00 that becomes free from $50.00, express shipping of $15.00 that is never free, and a limit of five per item.

JS Cart rules: totals, shipping and limits

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The subtotal of two mugs (2 x $12.99) plus one poster ($18.50) is $44.48, so shipping is the flat $5.00 and the tax is 3.5584 rounded to $3.56, giving $53.04. Adding stickers pushes the subtotal over $50, which makes standard shipping free. A mutation test is a good habit: change FREE_SHIPPING_FROM or the rounding and see which checks fail. If none do, your checks are too weak.

Selenium code for the journey

Here is the end-to-end test in Python. It uses a page object for the shop (see The Page Object Model), the Select helper for the dropdown (see Forms, Checkboxes and Dropdowns), and explicit waits (see Implicit, Explicit and Fluent Waits).

Python
import re
from decimal import Decimal

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select, WebDriverWait


def to_decimal(text):
    return Decimal(re.sub(r"[^0-9.]", "", text))


class ShopPage:
    CART_COUNT = (By.CSS_SELECTOR, "[data-testid='cart-count']")
    SHIPPING = (By.CSS_SELECTOR, "select[data-testid='shipping']")
    TOTAL = (By.CSS_SELECTOR, "[data-testid='order-total']")
    PLACE_ORDER = (By.CSS_SELECTOR, "[data-testid='place-order']")
    STATUS = (By.CSS_SELECTOR, "[data-testid='order-status']")
    ORDER_ID = (By.CSS_SELECTOR, "[data-testid='order-id']")

    def __init__(self, driver, base_url):
        self.driver = driver
        self.base_url = base_url
        self.wait = WebDriverWait(driver, 10)

    def open(self):
        self.driver.get(f"{self.base_url}/shop")
        return self

    def add_item(self, sku, times=1):
        button = (By.CSS_SELECTOR, f"[data-testid='add-{sku}']")
        for _ in range(times):
            self.driver.find_element(*button).click()
        return self

    def cart_count(self):
        return int(self.driver.find_element(*self.CART_COUNT).text)

    def choose_shipping(self, label):
        Select(self.driver.find_element(*self.SHIPPING)).select_by_visible_text(label)
        return self

    def total(self):
        return to_decimal(self.driver.find_element(*self.TOTAL).text)

    def place_order(self):
        self.driver.find_element(*self.PLACE_ORDER).click()
        return self

    def wait_for_confirmation(self):
        self.wait.until(EC.text_to_be_present_in_element(self.STATUS, "Order placed"))
        return self.driver.find_element(*self.ORDER_ID).text


def test_checkout_with_express_shipping(driver, base_url):
    shop = ShopPage(driver, base_url).open()
    shop.add_item("mug", times=2).add_item("poster")
    assert shop.cart_count() == 3
    assert shop.total() == Decimal("53.04")

    shop.choose_shipping("Express")
    assert shop.total() == Decimal("63.04")

    order_id = shop.place_order().wait_for_confirmation()
    assert re.fullmatch(r"#\d+", order_id)

A few details matter here:

  • to_decimal strips the currency symbol and any thousands separators before parsing. Compare Decimal values, never floats.
  • Select works on real <select> elements. It selects by visible text, value or index. Custom dropdowns made of <div> elements are not <select> elements, so you click them like any other element.
  • text_to_be_present_in_element is the wait for the asynchronous part. After you click "Place order", the status first reads "Processing..." and only later "Order placed". An immediate assert would be a race, as explained in Why Tests Need Waits.
  • Adding items twice with click() in a loop is fine here. If the page re-renders the button, locate it again each time instead of reusing a stored element, or you will meet a stale element error.

Waiting for the asynchronous checkout

Now let us see the race and the wait working together. The stand-in shop below finishes checkout after about a tenth of a second, like a real server round trip. The page object offers confirmation(), which polls until the status changes, and the last part shows what a timeout looks like when the condition never becomes true.

JS End-to-end checkout with an explicit wait

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the output in order. The totals match the unit-level numbers ($53.04, then $63.04 with express shipping). Immediately after the click the status is still "Processing...", so asserting "Order placed" there would fail intermittently, which is the textbook flaky test. The wait polls every 25 milliseconds and returns as soon as the condition is true, so it is as fast as the app allows. In the last block nothing ever places an order, and the wait ends with a TimeoutException whose message names what we were waiting for. Always write that message; "timed out" alone makes failures hard to read. The helper here is a stand-in for WebDriverWait, which behaves the same way: poll, ignore expected errors while polling, give up after a timeout.

Making the flow robust

  • Wait for outcomes, not time. time.sleep(5) makes the suite slow when the app is fast and flaky when it is slow.
  • Start from a known state. If the cart persists between sessions, an earlier run can leave items in it. Use a fresh user, clear the cart through an API, or add items through the API in the test setup and use the UI only for the part you are actually testing.
  • Keep test data controlled. Use test products with fixed prices, so a marketing team changing a price does not break your checks.
  • Never place real orders. Use a staging environment with a payment sandbox; see Security, Ethics and Scraping Limits.
  • Capture evidence. A screenshot and the page source on failure save hours; see Reporting and Logging.
  • Parallel safety. Orders create records. If several workers place orders as the same user, their assertions can collide; see Running in CI.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the project compare prices as cents or Decimal instead of floats?

    Binary floating point cannot store values like 0.1 exactly. Integers in cents, or Decimal, make money comparisons exact.
  2. 2. Right after clicking Place order the status reads "Processing...". What should the test do?

    The result arrives asynchronously. An explicit wait returns as soon as the condition holds and fails with a clear timeout otherwise.
  3. 3. Which class do you use for a real <select> shipping dropdown?

    Select wraps a <select> element and offers selection by visible text, value or index. Custom div-based dropdowns are clicked like ordinary elements.
  4. 4. Where is the best place to verify the tax rounding rule in detail?

    Calculations need no browser. Testing them below the UI is faster and pinpoints the cause, while the UI test checks the display.

Summary

  • Plan one user journey with checkpoints, but keep detailed rules in small focused tests or unit tests.
  • Compare money exactly: cents or Decimal, and test the rounding rule with a value that actually rounds.
  • Use Select for real dropdowns and test ids for stable locators.
  • Wait for the asynchronous result with an explicit condition and write a descriptive timeout message.
  • Start from a known state, use controlled test data, avoid real payments, and capture evidence on failure.
  • The stand-in shop mirrors the logic; the Python blocks are the real Selenium code and are read-only here.

Next, check a different kind of behavior in Project: Form Validation Checks.