首页 > 解决方案 > 赛普拉斯将响应正文中的内容保存为别名或变量

问题描述

cy.request用来创建一个新用户。我需要获取userID并使用它来组装一个 url。

例如:

function createUser () {
  cy.request({
    method: 'GET',
    url: `/human/sign_in`
  }).then(response => {
    const $ = cheerio.load(response.body)
    const token = $('css to get the token')
    cy.request({
      method: 'POST',
      url: `/signups/brands`,
      form: true,
      body: {
        'authenticity_token': token,
        'name': 'some name',
        'email': 'some email'
      }
    })
  }).then(response => {
    const $ = cheerio.load(response.body)
    const userID = $('css to get userID') // here's the userID
  })
}

如何返回 this userID,以及如何在下面的代码中引用它?

describe('some feature', () => {
  it('should do something', () => {
    createUser()
    cy.visit(`/account/${userID}`)      // how to refer to it?
  })
})

我查了官方文档。它似乎as()可以做一些伎俩。但是我找不到as()after使用的示例cy.request()

谢谢!

标签: cypress

解决方案


我们在测试中使用自定义命令做同样的事情并从那里返回值。带有返回的自定义命令将自动等待返回值,因此您不必担心异步问题或别名的麻烦。

Cypress.Commands.add("createUser", () {
  return cy.request({
    method: 'GET',
    url: `/human/sign_in`
  }).then(response => {
    const $ = cheerio.load(response.body)
    const token = $('css to get the token')
    cy.request({
      method: 'POST',
      url: `/signups/brands`,
      form: true,
      body: {
        'authenticity_token': token,
        'name': 'some name',
        'email': 'some email'
      }
    })
  }).then(response => {
    const $ = cheerio.load(response.body)
    return $('css to get userID') // here's the userID
  })
})

然后您的测试将如下所示:

describe('some feature', () => {
  it('should do something', () => {
    cy.createUser().then(userId => {
      cy.visit(`/account/${userID}`)
    })
  })
})

推荐阅读