table of contents Table of contents

How to Test Coupons and Discounts with Playwright

On this page

Webshops and subscription-based services often offer discounts through coupon codes. Applying a valid coupon code during checkout might reduce the price of one, several, or all items in the shopping cart.

Steps

While discount coupons will be applied in different ways depending on the service or shop they are relevant to, in most cases:

  1. Having selected one or more products will be a prerequisite for applying the coupon
  2. Entering a valid coupon will result in visible feedback, i.e. a reduction of the previous product/cart price

The following example, running against our test site, will add a variable number of items to the cart, then proceed to compare the total price before and after applying the coupon. The coupon is reducing the price of the whole shopping cart by 20%, therefore we will be asserting that the discounted price is reduced by the right amount. For this step we have chosen Chai, but any solid assertion library will do.

const assert = require('chai').assert
const { chromium } = require('playwright')
const productsNumber = process.env.PRODUCTS_NUMBER || 3

;(async () => {
  const browser = await chromium.launch()
  const page = await browser.newPage()

  await page.goto('https://danube-web.shop/')

  for (let i = 1; i <= productsNumber; i++) {
    await page.click(`.preview:nth-child(${i}) > .preview-author`)
    await page.click('.detail-wrapper > .call-to-action')
    await page.click('#logo')
  }

  await page.click('#cart')

  await page.waitForSelector('#total-price')
  const price = await page.$eval('#total-price', (e) => e.innerText)

  await page.click('.cart > label')
  await page.click('#coupon')
  await page.type('#coupon', 'COUPON2020')
  await page.click('.cart > div > button')

  const expectedDiscountedPrice = price * 0.8
  const discountedPrice = await page.$eval('#total-price', (e) => e.innerText)
  assert.equal(discountedPrice, expectedDiscountedPrice)

  await browser.close()
})()

Run in Checkly

Run this example as follows:

PRODUCTS_NUMBER=3 node coupon.js
SET PRODUCTS_NUMBER=3
node coupon.js

Takeaways

  1. We can simply verify that coupons are accepted, or also check that they command the right discount.
  2. Assertion libraries are useful when non-trivial assertions are required.

Last updated on November 6, 2024. You can contribute to this documentation by editing this page on Github