问题
I use cy.request to create a new user. I need to get the userID and use it to assemble a url.
e.g.:
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
})
}
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?
})
})
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().
Thanks!
回答1:
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}`)
})
})
})
回答2:
I think the simplest way to do this is to add some return statements to your function and use then() within your test. (Thanks to @soccerway for suggesting this)
function 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)
const userID = $('css to get userID') // here's the userID
return userID;
})
}
describe('some feature', () => {
it('should do something', () => {
createUser().then(userID => {
cy.visit(`/account/${userID}`)
})
})
})
来源:https://stackoverflow.com/questions/53701147/cypress-save-contents-in-response-body-as-a-alias-or-variable