首页 > 解决方案 > 如何在赛普拉斯测试中实现自定义命令

问题描述

我编写了一个自定义命令来从如下窗口获取身份验证令牌

Cypress.Commands.add("getToken", AUTH => {
 return cy.window().then(window => window.localStorage.getItem(AUTH));
});
const authToken = JSON.parse(window.localStorage.getItem("AUTH")); 

authToken = returned the authtoken. I want to know how to make`enter code here` this as 
function/custom command so that the other t`enter code here`est could use this.

标签: cypresscucumberjs

解决方案


我建议这样的事情:

describe('', () => {
  let tokens = {};

  it('', () => {
    cy
      .getToken('AUTH', ({ token }) => {
        Object.assign(tokens, { auth: token });
      })
      .request({
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${tokens.auth}`, }
      })

  });
});

您还必须更改一点getToken命令:

Cypress.Commands.add("getToken", (AUTH, cb) => {
 return cy.window().then(window => cb(window.localStorage.getItem(AUTH)));
});


推荐阅读