logo

Just A Dev

article cover image

Automate UI testing with Cypress - Day 2

article cover image

Chuong DangFebruary 21, 2024

Automate UI testing with Cypress - Test login form

Next step, login form

In the last article, I mentioned about the login feature, but didn't show you how to do it with Cypress. So let me make it up for you.

In case you didn't read my first article, here's it is.

Let's start Cypress again with this command

yarn run cypress open

Click on New spec button cypress-day2-step1.png

Let's name this spec linked-login.cy.js

Open VSCode, you'll see something like this

cypress-day2-step2.png

Replace the code by this

describe('Linked login', () => { it('Should login successfully', () => { cy.visit('https://linkedin.com') }) })

And return to Chrome window, you'll see the login form, obviously cypress-day2-step3.png

Now, the question is how can you input data in username and password fields? Basically, you just need to find identification of those fields, then tell Cypress to fill values into them. I'll guide you through it.

Right click on the username field, choose Inspect cypress-day2-step4.png

This is what you'll see cypress-day2-step5.png

Do you notice that in the right side of the window, there's a block of code which contains <input ..... id="session_key" />? This is what we want to find.

Now let's try to tell Cypress to input the value into this field by adding these code behind cy.visit part

const usernameField = cy.get("input#session_key") // Check whether the input is visible usernameField.should("be.visible"); // Click on the input field usernameField.click(); // Type value for the input usernameField.type("[email protected]");

Basically you tell Cypress to find the input element with ID (#) = session_key. Then check whether it's visible. If yes then click on it, and type a value for that field. Really simple.

And this is the result. Interesting right? cypress-day2-step6.png

Do the same for password, this is the homework for you :D

Let's go ahead with the Sign in button. Now we need to click on it to perform login action right? Right click on it, then Inspect and we'll see this cypress-day2-step7.png

This is a little tricky, since we don't see any ID of this button. But take a closer look, then we'll see this part, which quite equivalent to an ID

data-id="sign-in-form__submit-btn"

Now let's add this into the code

const loginButton = cy.get('button[data-id=sign-in-form__submit-btn]') loginButton.click()

By this, you'll tell Cypress to find a button which has attribute data-id = sign-in-form__submit-btn, then click it. And this is the result cypress-day2-step8.png

Now it's up to you to assert which case is failed and which is passed.

Ohhh, I forgot to tell you. You should try to test on another site. This is just an example. If you test on Linkedin too much you'll be blocked. Muahahahaha!!!

Have a good day. Here's a carrot for you :D IMG_7957.JPG