赛普拉斯:从 API 获取令牌,然后保存在本地存储中并在另一个 API 的标头中使用,然后返回第二个 API 的响应正文



我有一个API(我们称之为getToken(在其响应正文中生成令牌。然后,我调用该令牌并存储在另一个 API 的标头中(我们称之为returnBody(。将localStorage用于getTokenAPI是有意义的,因为此令牌可重用于多个API。但是,如果我需要返回/显示后续 API 的响应正文(例如returnBody(,我不确定使用localStorage。在 API 的函数/命令中,它会记录响应正文。但是,当我通过测试文件调用它时,它会生成null。 示例代码如下:

命令.js:

Cypress.Commands.add('getToken', () => { //API to generate token
cy.request({
method: 'POST',
url: 'https://someAPItoGenerateToken',
form: true, //sets to application/x-www-form-urlencoded
body: {
grant_type: 'credentials',
scope: 'all-apis'
},
auth: {
username: Cypress.env('api_username'),
password: Cypress.env('api_password')
}
})
.its('body')
.then(bearerToken => {
cy.setLocalStorage('bearerToken', JSON.stringify(bearerToken))
cy.log('Token generated: ' + bearerToken.token)
}
)
})
Cypress.Commands.add('returnBody', (url, token) => { //API to return some values
return cy.request({
method: 'GET',
url: url,
auth: {
bearer: token
}
})
.then((response) => {
// Stringify JSON the body.
let body = JSON.stringify(response.body)
cy.log(body)
})
})

测试文件:

describe('Return value of 2nd API', ()=> {
before(() => {
cy.getToken() //Run this once to generate token for the entire test suite
cy.saveLocalStorage()
})
beforeEach(() => {
cy.restoreLocalStorage()
})
it('Return value of 2nd API', () => {
cy.getLocalStorage('bearerToken').should('exist')
cy.getLocalStorage('bearerToken').then(bearerToken => {
const tokenJSON = JSON.parse(bearerToken)
const url = 'https://someAPItoReturnJSONbody'
cy.returnBody(url, tokenJSON.token).then((returned_value) => {
cy.log(returned_value)
})
})
})
})

返回正文命令中的 body 返回 JSON 响应。但是,测试文件中的returned_value显示 null。

正如本期评论的那样:"您不能从自定义命令返回第三方承诺,因为这会破坏 cypress 命令之间的链接。这是因为 .then 方法不一样。

因此,只需将请求正文返回为:

Cypress.Commands.add('returnBody', (url, token) => {
return cy.request({ /* options */ })
.its("body");
});

然后,在测试中,您可以执行以下操作:

it("should return foo value", () => {
cy.returnBody(url, token).then(returned_value => {
cy.log(returned_value);
expect(returned_value).to.deep.equal("foo-value");
})
})

您可能需要从returnBody任务返回响应正文:

Cypress.Commands.add('returnBody', (url, token) => {
return cy.request({ /* options */ })
.then(response => {
let body = JSON.stringify(response.body);
Cypress.log(body);
return body; // Add this line
});
});

另一种方法是使用固定装置将令牌存储在柏树侧。

fixture.json:

{"bearerToken":""
.
.
.}

命令.js:

cy.fixture('testData.json').as('testData')
.
.
.then(bearerToken => {
this.testData.bearerToken = JSON.stringify(bearerToken)
cy.log('Token generated: ' + bearerToken.token)
}
)

测试.js

describe('Return value of 2nd API', ()=> {
before(() => {
cy.getToken() //Run this once to generate token for the entire test suite
})
it('Return value of 2nd API', () => {
cy.fixture('testData.json').as('testData')
.then(testData => {
const tokenJSON = JSON.parse(testData.bearerToken)
const url = 'https://someAPItoReturnJSONbody'
cy.returnBody(url, tokenJSON.token).then((returned_value) => {
cy.log(returned_value)
})
})
})
})

相关内容

最新更新