我有這段代碼可以使用保存的 API 令牌并在其他測驗中使用它,但它不起作用(我收到此錯誤訊息:參考錯誤:未定義 access_token:所以我需要保存生成的令牌并將其用于所有我的 API 測驗
const API_STAGING_URL = Cypress.env('API_STAGING_URL')
describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
method:'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers:{
authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}}).then((response)=>{
expect(response.status).to.eq(200)
const access_token = response.body.access_token
cy.log(access_token)
cy.log(this.access_token)
})
cy.log(this.access_token)
}),
it('Create Cart',function(){
cy.request({
method:'POST',
url: `${API_STAGING_URL}` "/api/v1/cart",
headers:{
Authorization : 'Bearer ' access_token,
"Content-Type": 'application/json',
"Cache-Control": 'no-cache',
"User-Agent": 'PostmanRuntime/7.29.2',
"Accept": '*/*',
"Accept-Encoding": 'gzip, deflate, br',
"Connection": 'keep-alive',
"Postman-Token": '<calculated when request is sent>'
},
}}).then((response)=>{
//Get statut 200
expect(response.status).to.eq(200)
//Get property headers
})})
})
uj5u.com熱心網友回復:
這是一個范圍問題 -access_token在創建它的塊之外不存在。Filip Hric 有一篇關于在 Cypress 中使用變數的精彩博客文章。我最喜歡的策略是將值存盤在賽普拉斯環境變數中。
const API_STAGING_URL = Cypress.env('API_STAGING_URL');
describe('Decathlon API tests', () => {
it('Get token', function () {
cy.request({
method: 'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers: {
authorization: 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}
}).then((response) => {
expect(response.status).to.eq(200);
Cypress.env('access_token', response.body.access_token);
cy.log(Cypress.env('access_token'));
});
});
it('Create Cart', function () {
cy.request({
method: 'POST',
url: `${API_STAGING_URL}` '/api/v1/cart',
headers: {
Authorization: `Bearer ${Cypress.env('access_token')}`,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'User-Agent': 'PostmanRuntime/7.29.2',
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br',
Connection: 'keep-alive',
'Postman-Token': '<calculated when request is sent>'
}
}).then((response) => {
// Get statut 200
expect(response.status).to.eq(200);
// Get property headers
});
});
});
uj5u.com熱心網友回復:
另一種方法是在掛鉤中創建 access_token,然后您可以在 it() 塊中訪問它。
有幾種方法可以做到這一點。
使用變數:
let text
beforeEach(() => {
cy.wrap(null).then(() => {
text = "Hello"
})
})
it("should have text 'Hello'", function() {
// can access text variable directly
cy.wrap(text).should('eq', 'Hello')
})
使用別名:
beforeEach(() => {
cy.wrap(4).as("Number")
})
it("should log number", function() {
// can access alias with function() and this keyword
cy.wrap(this.Number).should('eq', 4)
})
這是一個作業示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520747.html
標籤:谷歌浏览器自动化测试柏
