赛普拉斯将响应正文中的内容另存为别名或变量 [英] Cypress save contents in response body as a Alias or variable

查看:75
本文介绍了赛普拉斯将响应正文中的内容另存为别名或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use cy.request to create a new user. I need to get the userID and use it to assemble a 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
  })
}

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

How to return this userID, and how to refer to it in the following codes?

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

我查阅了官方文件。看来 as()可以起到一些作用。但是我找不到在 cy.request()之后使用 as()的示例。

I looked up the official documents. It seems as() could do some trick. But I couldn't find an example to use as() after cy.request().

谢谢!

推荐答案

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

We do the same thing in our tests using a custom command and return the value from there. A custom command with a return will automatically wait for the return value so you don't have to worry about async issues or the hassle of aliases.

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
  })
})

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

Then your test would look like this:

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

这篇关于赛普拉斯将响应正文中的内容另存为别名或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆