Imagine you have a product store like the one I am using in the course Swag Store. Some of the items are new, so the inventory page marks them with a "NEW" badge
The badge is implemented using a pseudo-element ::after
1 | .inventory_item_name { |
The React component simply sets the inventory_new_item_badge
class based on the passed prop badge
.
1 | <div |
How can we confirm the badge is present and has the expected text NEW
? Easy. We can get the style of the HTML element and get its style property
1 | const newItemTitle = 'Sauce Labs Bike Light' |
Tip: I have similar examples under "Recipes" on my site https://glebbahmutov.com/cypress-examples
What if the badge appears after some delay? cy.then(callback)
does not retry, so we can make the above code retry-able using cy.should(callback)
since it does not execute any Cypress commands:
1 | // test the ::after element with retries |
We can improve the above by noticing the individual steps:
const after = window.getComputedStyle($el[0], '::after')
is simply calling a functionwindow.getComputedStyle
on the current subject's first element with the argument::after
. We can write the same code using a query from cypress-map
1 | cy.contains('.inventory_item_name', newItemTitle) |
- The above query yields the pseudo-element. We now have to get the property
content
likeconst afterContent = after.getPropertyValue('content')
. That is a standardcy.invoke
command
1 | cy.contains('.inventory_item_name', newItemTitle) |
- the final assertion inside the
cy.should(callback)
is the explicitexpect(afterContent).to.equal('"NEW"')
. If theafterContent
is the subject, we can write it using an implicitshould('equal', value)
assertion completing our refactoring
1 | cy.contains('.inventory_item_name', newItemTitle) |
It works, as the screenshot below shows
A dot pseudo-element
Sometimes a pseudo-element is used to simply show a graphical element to get the user's attention. In the next example, a red dot is shown next to the cart icon if the cart has items.
The CSS markup for the pseudo-element has no content, just background-color
1 | .shopping_cart_link_with_items::after { |
We can use the background color to verify the dot's presence and absence. For example, let's write a test that confirms that:
- there is no dot initially
- a dot appears when the user adds an item to the cart
- a dot disappears when the cart becomes empty again
We can even make our life harder by adding a delay between the click and the cart update.
1 | // a couple of helper functions for simplicity and readability |
Here is the test in action:
Nice!
🎓 This blog post is based on hands-on lessons in my course Testing The Swag Store. Take a look at the lessons Bonus 62: Testing the ::after pseudo-element and Bonus 63: Confirm a dot pseudo-element.