如何在Cypress中发送urlencode模式的POST请求获取AccessToken?
在Cypress中发送urlencode格式的POST请求获取AccessToken
你可以用Cypress内置的cy.request()方法实现这个需求,以下是对应Postman脚本的Cypress实现:
cy.request({ method: 'POST', url: 'https://login.microsoftonline.com/967731f1/oauth2/v2.0/token', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: '459e40d6-e96a-4c4e-833f-f43bd5d71885', scope: 'api://icy-beach-05c371d10.1.azurestaticapps.net/459e40d6-e96a-4c4e-833f-f43bd5d71885/access-as-user', grant_type: 'password', username: 'abc@gmail.com', password: 'xxxxxx' }).toString() }).then((response) => { // 验证请求是否成功 expect(response.status).to.eq(200); // 将access_token存入Cypress环境变量 Cypress.env('accesstoken_admin', response.body.access_token); // 可选:如果需要在前端页面使用令牌,可存入localStorage // cy.window().then(win => { // win.localStorage.setItem('accesstoken_admin', response.body.access_token); // }); });
关键细节说明:
- 请求体处理:用
URLSearchParams把键值对对象转成urlencode格式的字符串,和Postman的urlencoded模式效果完全一致。 - 请求头设置:必须指定
Content-Type为application/x-www-form-urlencoded,确保服务器能正确解析请求体。 - 令牌存储:通过
Cypress.env()把令牌存入环境变量,后续测试用例里直接用Cypress.env('accesstoken_admin')就能调用。 - 响应断言:添加
expect(response.status).to.eq(200)确保请求成功,还可以追加断言验证令牌是否存在:expect(response.body).to.have.property('access_token');
复用逻辑优化(可选):
如果多个测试用例都需要获取令牌,可以把这段逻辑封装成自定义命令。在cypress/support/commands.js中添加:
Cypress.Commands.add('getAccessToken', () => { return cy.request({ method: 'POST', url: 'https://login.microsoftonline.com/967731f1/oauth2/v2.0/token', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: '459e40d6-e96a-4c4e-833f-f43bd5d71885', scope: 'api://icy-beach-05c371d10.1.azurestaticapps.net/459e40d6-e96a-4c4e-833f-f43bd5d71885/access-as-user', grant_type: 'password', username: 'abc@gmail.com', password: 'xxxxxx' }).toString() }).then(response => { Cypress.env('accesstoken_admin', response.body.access_token); return response.body.access_token; }); });
之后在测试用例里直接调用:
cy.getAccessToken().then(token => { // 使用令牌执行后续操作 });
内容的提问来源于stack exchange,提问作者hanh nguyen
相关产品推荐
相关产品推荐

