如何在赛普拉斯测试中实现自定义命令

时间:2020-02-27 09:23:59

标签: cypress cucumberjs

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

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.

1 个答案:

答案 0 :(得分:1)

我建议这样:

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)));
});