Cypress将响应正文中的内容保存为别名或变量
我使用Cypress将响应正文中的内容保存为别名或变量,cypress,Cypress,我使用cy.request创建一个新用户。我需要获取用户ID,并使用它来组装url e、 g: 如何返回此用户ID,以及如何在以下代码中引用它 describe('some feature', () => { it('should do something', () => { createUser() cy.visit(`/account/${userID}`) // how to refer to it? }) }) 我查阅了官方文件。似乎as(
cy.request
创建一个新用户。我需要获取用户ID
,并使用它来组装url
e、 g:
如何返回此用户ID
,以及如何在以下代码中引用它
describe('some feature', () => {
it('should do something', () => {
createUser()
cy.visit(`/account/${userID}`) // how to refer to it?
})
})
我查阅了官方文件。似乎as()
可以起到一些作用。但是我找不到在cy.request()
之后使用as()
的示例
谢谢 我们在测试中使用a执行相同的操作,并从中返回值。带有返回的自定义命令将自动等待返回值,因此您不必担心异步问题或别名问题
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}`)
})
})
})
我认为最简单的方法是向函数中添加一些返回语句,并在测试中使用
then()
。(感谢@soccerway的建议)
函数createUser(){
返回请求({
方法:“GET”,
url:`/human/sign_in`
})。然后(响应=>{
const$=cheerio.load(response.body)
const-token=$('css-to-get-the-token')
赛义德请求({
方法:“POST”,
url:`/signups/brands`,
形式:对,
正文:{
“真实性令牌”:令牌,
“名字”:“某个名字”,
“电子邮件”:“一些电子邮件”
}
})
})。然后(响应=>{
const$=cheerio.load(response.body)
const userID=$('css to get userID')//这是userID
返回用户标识;
})
}
描述('some feature',()=>{
它('应该做点什么',()=>{
createUser()。然后(userID=>{
cy.visit(`/account/${userID}`)
})
})
})
createUser()函数是否为您返回正确的userID
?@soccerwaycreateUser()将返回一个承诺,这正是我所困惑的。如果直接返回userID
,它将为null。这也是一个很好的答案,请注意,测试套件可能需要在所有测试中使用一个userID
值,在这种情况下,您需要在before中调用自定义命令,并在Cypress别名中访问它(cy.wait(“@userID”
)。您可以在before()
中使用它,或者将userId
存储在before()
块范围之外的变量中,或者更好地使用Cypress.Cookies.preserveOnce(“yourSessionCookie”)
这样您就不需要在每次测试之前登录。Richard…将执行上述cy.request()
Cypress中SSO模型的示例工作?。需要接收令牌并重定向到其他url吗?在我的Cypress测试中,我与Microsoft一起获得了一个SSO场景,获取凭据,然后系统将重定向到另一个url
,您认为上述方法可行吗?如果您能回答这一问题,那将非常棒,我的问题在这里,please…@soccerway,我对SSO了解不多,但这个问题的模式与文档中显示的类似,似乎表明这是可能的。主要区别是您希望将令牌传递回,而Cypress则在中使用令牌(response=>{…
,因此您必须小心在实际返回令牌之前使用令牌触发的后续测试。我通常将此类代码包装在before()
中,以确保它先于任何其他代码运行。当我尝试使用表单提交重定向时,它表示未定义parseOutMyToken。
describe('some feature', () => {
it('should do something', () => {
cy.createUser().then(userId => {
cy.visit(`/account/${userID}`)
})
})
})