如何在其他 .js 文件中获取 Cypress 中的 cy.wrap 数据

huangapple go评论72阅读模式
英文:

How to get cy.wrap data in other .js file Cypress

问题

尝试将这段代码放入command.js中以创建一个生成登录令牌的通用函数。

const data = require('../fixtures/User_data.json');

Cypress.Commands.add('get_token', () => { 
    cy.api({
        method: "POST",
        url: "https://api-stg.sample.com/login",
        body: {
            "mobile_number": "+91" + data.mobile,
            "password": "p@ssw0rd"
        }
    })
    .then((response) => {
        const token = response.body.data.access_token.token;
        cy.log("Bearer token: " + token);
        cy.wrap(token).as('token');
    });
});

然后,在我的测试规范文件中,

create_mobilenum() {
    cy.get_token();
    cy.api({
        method: "POST",
        url: "https://api-stg.sample.com/mobile_numbers",
        headers: { 'Authorization': "Bearer " + ('@token') },
        // ...
        // ...
    });
}

但在Cypress仪表板中,我无法登录,因为在运行我的规范文件时返回“token未定义”。

英文:

tried to put this in command.js to create a generic function that generates token when login.

const data = require('../fixtures/User_data.json')

Cypress.Commands.add('get_token', () => { 
    cy.api({
        method: "POST",
        url:    "https://api-stg.sample.com/login",
        body: 
        {
        "mobile_number": "+91" + data.mobile,
        "password": "p@ssw0rd"  
        }
      })
        .then((response) => {
          const token = response.body.data.access_token.token
          cy.log("Bearer token: " + token )
          cy.wrap(token).as('token')
      })
    })

then in my test spec file ,

      create_mobilenum () {
        cy.get_token()
        cy.api({
          method: "POST",
          url:    "https://api-stg.sample.com/mobile_numbers",
          headers: { 'Authorization': "Bearer " + ('@token')  },
          ...
          ...

but in cypress dashboard , I cannot login because it returns token is undefined when my spec file runs .

答案1

得分: 1

从我所阅读的Variables and Aliases来看,这不是如何使用别名。

它们不像变量一样工作,您需要提取该值

cy.get('@token').then(token => {
  cy.api({
    ...
    headers: { 'Authorization': "Bearer " + token  },
英文:

From what I've read Variables and Aliases, that's not how to use an alias.

They don't act like variables, you will need to extract the value

cy.get('@token').then(token => {
  cy.api({
    ...
    headers: { 'Authorization': "Bearer " + token  },

huangapple
  • 本文由 发表于 2023年4月17日 19:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定