Recently I saw a Linkedin post showing how to highlight an element and take the page screenshot using Selenium and Playwright test runners.
Another user commented with a similar test for Playwright
In both cases we highlight an element by modifying its style. We can do the same highlight ourselves on any page by simply opening the DevTools and changing the style
object of any element. Here is my setting the border of the input search box on my favorite search engine Ecosia
Cypress test
Let's see how we can do the same using Cypress.
1 | it('highlights the input element', () => { |
🎁 You can find the code shown in this blog post in the repo bahmutov/highlight-element-example.
A couple of notes about this test:
- the base url is set in the
cypress.config.js
file, so in the test I can simply visit the root usingcy.visit('/')
- Cypress query commands like cy.get yield a jQuery object once the element is found. For now I simply used the DOM element
$el[0].style = ...
- I clipped the captured screenshot using cy.screenshot command because Ecosia homepage is very tall by default and I am only interested in showing the input element.
Code runs in the browser
Cypress is different from other test runners. Selenium and Playwright tests run in Node.js environment, sending the commands to "get an element", "take a screenshot" to the browser using some protocol. Cypress test runs inside the browser. Thus you don't need to "inject" JavaScript which sends the stringified code from Node.js. You can even use local variables, register callbacks, etc - all from the test. No argument marshaling or serialization.
1 | // normal Cypress test code, works just as well |
jQuery
Cypress wraps all found elements in a jQuery object by default. This makes it simple to use one of the jQuery's many methods to work with DOM elements. For example, we could set multiple CSS properties at once
1 | const border = '3px solid red' |
Fluent chain
In the test above we get the element, which the test yields to the next command.
1 | cy.get(...) |
Inside the cy.then
callback the test invokes the method "css" and that's it. We can invoke a method by name and pass arguments using the built-in Cypress command cy.invoke
1 | const border = '3px solid red' |
Works exactly the same.
Cool trick because Cypress comes with TypeScript types, when I write cy.get(...).invoke(...)
my code editor understands the available jQuery methods we can invoke on the current subject.
Nice.
Side by side
Which solution do you prefer?
I will open a poll on each social network to see what people think
See also
Tip: I have a little plugin cypress-highlight for Cypress users that lets you quickly highlight found elements
1 | // highlight all elements with test attributes |
I don't have a Selenium course, but you can practice solving the same testing problems using Cypress and Playwright in my course Cypress vs Playwright. I wonder which solution you would prefer in each case.