eba*_*ter 7 javascript api rest automation cypress
我有一个生成令牌的 Rest API。此会话令牌在多个 REST API 中用作授权承载令牌。我用它作为参考:https : //github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__jwt/cypress/integration/spec.js
但是,在该示例中,生成令牌的函数嵌入在测试中。我试图创建一个自定义命令,它应该存储在本地,但它没有被测试选中。请注意,自定义命令中不包含返回值。
我在support/commands.js下面的代码:
let identity
Cypress.Commands.add('postToken', () => {
cy.request({
method: 'POST',
url: Cypress.env('api_identity_url'), //get from cypress.env.json
form: true, //sets to application/x-www-form-urlencoded
body: {
grant_type: 'client_credentials',
scope: 'xero_all-apis'
},
auth: {
username: Cypress.env('api_identity_username'),
password: Cypress.env('api_identity_password')
}
})
.its('body')
.then((response) => {
identity = response
window.localStorage.setItem('identity', JSON.stringify(identity))
cy.log(identity.access_token)
})
})
Run Code Online (Sandbox Code Playgroud)
我的测试:
context('Check token details', () => {
it('Check token', () => {
cy.postToken()
const bToken = window.localStorage.getItem('identity')
cy.log(bToken)
})
})
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,日志显示null
“身份”的值。但是,它显示了我放置的自定义命令中的当前值cy.log(identity.access_token)
我尝试使用cy.writeFile但我认为这不是一个干净的方法。必须有某种方式可以在函数和不同的类之间传递数据。
示例 JSON 格式:
{
"token": "<this is the value I would like to use for other API's authorisation bearer token>",
"expires_in": 1200,
"token_type": "Bearer"
}
Run Code Online (Sandbox Code Playgroud)
您可以使用cypress-localstorage-commands package to persist localStorage between tests.
In support/commands.js
:
import "cypress-localstorage-commands";
Cypress.Commands.add('postToken', () => {
cy.request({
method: 'POST',
url: Cypress.env('api_identity_url'), //get from cypress.env.json
form: true, //sets to application/x-www-form-urlencoded
body: {
grant_type: 'client_credentials',
scope: 'xero_all-apis'
},
auth: {
username: Cypress.env('api_identity_username'),
password: Cypress.env('api_identity_password')
}
})
.its('body')
.then(identity => {
cy.setLocalStorage("identity_token", identity.token);
});
});
Run Code Online (Sandbox Code Playgroud)
Inside your tests:
describe("postToken", ()=> {
before(() => {
cy.postToken();
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
it("should exist identity in localStorage", () => {
cy.getLocalStorage("identity_token").should("exist");
cy.getLocalStorage("identity_token").then(token => {
console.log("Identity token", token);
});
});
it("should still exist identity in localStorage", () => {
cy.getLocalStorage("identity_token").should("exist");
cy.getLocalStorage("identity_token").then(token => {
console.log("Identity token", token);
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9736 次 |
最近记录: |