cypress - 赛普拉斯将响应正文中的内容保存为别名或变量
问题描述
我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.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}`)
})
})
})
推荐阅读
- shell - 使用 awk 从文件或 EV 中获取环境变量以将其用作 EV
- python-3.x - 根据 Pandas 中的同比变化和上一年的值计算多列的当前值
- c - 跳过第二个学生姓名,请给出如何解决这种情况并修复的解决方案。使用结构
- node.js - 将 api 响应迭代为 html
- google-cloud-platform - 应授予查看 Google Cloud SQL 图表的哪些权限?
- javascript - 在 React 组件的 render 方法上,如何将 prop 仅应用于地图/数组中的一项?
- c++ - C++中的accumulate(a.begin(), a.end(), 0) 或accumulate(a.begin(), a.end(), 0ll) 之间有什么区别吗?
- c# - 为什么本地 Service Fabric 无权访问我的证书的私钥?键集不存在
- flutter - 颤振将PDF数据发送到打印机
- sql - SSRS SUM() 组外的分组值