英文:
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  },
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论