This article is a part of series on Cypress basics. You can check out some other articles on my blog where I provide step by step explanations of some Cypress basics + some extra tips on how you can take things one step further. So far, I wrote about:
To get proper attributes of an element, it’s good to understand some basics of different HTML elements. Let me give you an example. Let’s say we have two elements:
During my test, I’m going to fill the input field and then check if the text has correct text inside. With both of these elements, you can see the text on page. But if I want to "check text" on these elements, I need to use slightly different approach with each:
The difference here is, that our div
element contains a certain text, but input
elements in HTML are used for inserting value. I strongly suggest checking out W3Schools docs to explore different types of input form fields.
You may be in a situation where you need to check your links. In that case, getting your href
attribute from anchor element would be useful. Let’s say we have a following link:
To check the href
attribute, you can write a test like this:
In addition, you can test if the link is actually valid, by making an http request to it:
By using .invoke('prop')
, you can access many different properties from selected element. The whole list of that properties can be found in Chrome DevTools. To access them, click on the given element and open properties panel.
As you can see, there are tons of options. For example, we can use .invoke()
command to look into whether checkbox element is checked.
Remember how we tested the value of a certain input? With .invoke()
we can pass the value of that input to another function, like this:
In the past, I had a bad input element in my app that would re-render during my test and delete my input in the test. I would write a special "type and check" command that would retry if the input would not work properly.
This is definitely very hacky solution. I’d recomment checking out this great blog on identifying code smells (as the described situation is definitely one!) or looking into Gleb Bahmutov’s blog about the topic of when can a test start typing.
The other interesting thing about .invoke()
val is that by passing a second argument to this function will enable you to change the value and (kinda) simulate pasting a text to an textarea. I wrote about this in a recent blog for egghead.io, so give that a read. The simple example goes something like this:
Hope you like this. If you did, you can subscribe to a newsletter to get notified about a new article every week. You can also follow me on Twitter or LinkedIn.
From time to time I send some useful tips to your inbox and let you know about upcoming events. Sign up if you want to stay in loop.