I have the following code and idea and I want to make it functional so that I can log in to the test with the function as cy.login (live, username):
Cypress.Commands.add("login", (env,username) => {
env = Cypress.env('staging')
env = Cypress.env('live')
username = Cypress.username('username1')
username = Cypress.username('username2')
cy.get('input[name="Parameter.UserName"]').type('username')
cy.get('input[name="Parameter.Password"]').type('password1')
cy.contains('Login').click()
})
Certainly my code is not a functional one, but I want to understand the idea and how to write it in order to be able to use a variable several times.
And in cypress.json
{"env": {
"staging": "https://staginglink",
"live": "https://livelink"
}}
{"username": {
"username1": "username": "username1", "password" : "password1" ,
"username2": "username": "username2", "password" : "password2" ,
}}
Start with a fix to cypress.json
{
"env": {
"links": {
"staging": "https://staginglink",
"live": "https://livelink"
}
"users": {
"user1": {"username": "username1", "password" : "password1"},
"user2": {"username": "username2", "password" : "password2"},
}
}
Calling with string parameters:
cy.login('live', 'user2')
Command:
Cypress.Commands.add("login", (requiredEnv, requiredUser) => {
const links = Cypress.env('links'); // links section above
const link = links[requiredEnv]; // if passed "live" or "staging", gives the
// correct property of links section
cy.visit(link)
const users = Cypress.env('users'); // users section above
const user = users[requiredUser];
const username = user.username; // "user1" -> gives "username1"
// "user2" -> gives "username2"
const password = user.password; // "user1" -> gives "password1"
// "user2" -> gives "password2"
cy.get('input[name="Parameter.UserName"]').type(username) // don't put quotes around variable
cy.get('input[name="Parameter.Password"]').type(password) // don't put quotes around variable
cy.contains('Login').click()
})
In your Cypress.json you can arrange your data like this:
{
"env":{
"staging":"https://staginglink",
"live":"https://livelink"
},
"users":{
"user1":{
"username":"username1",
"password":"password1"
},
"user2":{
"username":"username2",
"password":"password2"
}
}
}
Then in your test you can access the data like:
Cypress.config('users').user1.username. //gets username1
Cypress.env('staging'). //gets staging link
Your custom command will look like:
Cypress.Commands.add('login', (user, env) => {
cy.visit(env)
cy.get('input[name="Parameter.UserName"]').type(user.username)
cy.get('input[name="Parameter.Password"]').type(user.password)
cy.contains('Login').click()
})
From your test you can write:
cy.login(Cypress.config('users').user1, Cypress.env('staging'))
cy.login(Cypress.config('users').user2, Cypress.env('live'))