Yes, Cypress
supports the ability to create and reuse actions and state in your UI, such as registering and logging in before a test.
However, Cypress
, through cy.request()
allows you to control the state of the browser more powerfully than a user would, making your tests simpler, faster, more reliable
Check out this example below where cy.request
is used to create/read state on your server.
In commands/index.js
:
Cypress.Commands.add('login', (user) => {
cy.request('POST', `${apiUrl}/users/login`, user)
})
Cypress.Commands.add("register", (user) => {
cy.request('POST', `${apiUrl}/users/register`, user)
})
Cypress.Commands.add('getUser', (username) => {
return cy.request('GET', `${apiUrl}/users/${username}`)
})
in register.spec.js
:
it ('can register', () => {
const user = {
name: 'jake',
email: '[email protected]',
password: '12345'
}
cy.visit('/register')
cy.get('input[name="name"]').type(user.name)
cy.get('input[name="email"]').type(user.email)
cy.get('input[name="password"]').type(user.password)
cy.get('input[name="password-confirm"]').type(user.password)
cy.get('input[type="submit"]').click()
// ensure register page sends you /home after register
cy.url().should('contain', '/home')
// expect user from server to match user from test
cy.getUser(user.name)
.then((dbUser) => expect(dbUser).to.deep.eql(user))
})
in login.spec.js
:
it('can log in', () => {
const user = {
name: 'jane',
email: '[email protected]',
password: '12345'
}
// register w/out UI
cy.register(user)
cy.visit('/login')
cy.get('input[name="name"]').type(user.name)
cy.get('input[name="password"]').type(user.password)
cy.get('input[type="submit"]').click()
// ensure the login page sends you home after login
cy.url().should('contain', '/home')
})
in userSettings.spec.js
:
it('can change email', () => {
const user = {
name: 'jane',
email: '[email protected]',
password: '12345'
}
// register and login w/o UI
cy.register(user)
cy.login(user)
cy.visit('/settings')
cy.get('input[name="email"]').type('[email protected]')
cy.get('input[type="submit"]').click()
cy.getUser(user.name)
.then((dbUser) => expect(dbUser.email).to.eql('[email protected]'))
})
.then(email => {window.localStorage.setItem('registration-email', email) })
– user8745435