首页 > 其他 > 详细

[Cypress] Combine Custom Cypress Commands into a Single Custom Command

时间:2020-03-03 20:02:14      阅读:71      评论:0      收藏:0      [点我收藏+]

It’s pretty likely that we’ll need to login as a particular user for many tests, let’s take our cy.request command and turn it into a custom command to make it easier for the places we’ll be needing a logged in user.

 

commands.js:

Cypress.Commands.add(‘createUser‘, overrides => {
  const user = buildUser(overrides)
  cy.request({
    url: ‘http://localhost:3000/register‘,
    method: ‘POST‘,
    body: user,
  }).then(response => ({...response.body.user, ...user}))
})

Cypress.Commands.add(‘login‘, user => {
  return cy
    .request({
      url: ‘http://localhost:3000/login‘,
      method: ‘POST‘,
      body: user,
    })
    .then(response => {
      window.localStorage.setItem(‘token‘, response.body.user.token)
      return {...response.body.user, ...user}
    })
})

Cypress.Commands.add(‘loginAsNewUser‘, () => {
  cy.createUser().then(user => {
    cy.login(user)
  })
})

 

spec.js:

describe(‘authenticated calculator‘, () => {
  it(‘displays the username‘, () => {
    cy.loginAsNewUser().then(user => {
      cy.visit(‘/‘)
        .findByTestId(‘username-display‘)
        .should(‘have.text‘, user.username)
        .findByText(/logout/i)
        .click()
        .findByTestId(‘username-display‘)
        .should(‘not.exist‘)
    })
  })
})

 

[Cypress] Combine Custom Cypress Commands into a Single Custom Command

原文:https://www.cnblogs.com/Answer1215/p/12404055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!