从 cypress 自定义命令返回值并在 test.cy.js 文件中的另一个函数中重用

问题描述 投票:0回答:1

我在commands.js 中创建了一个自定义命令 cy.createUser("userCreate") 来创建“userID”

Cypress.Commands.add("createUser", (payload) => {
    cy.makeUserviaAPI(payload).then((userID) => {
    cy.openUserProfile(userID);
    })
});

我想在我的 test.cy.js 文件中的其他方法中使用这个usedID。即我想在新方法 cy.updpateUser(userID) 中将 userID 作为变量传递

beforeEach(() => {
    cy.createUser("userCreate")
    cy.updpateUser(userID)
});

我尝试过以下修改:

Cypress.Commands.add("createUser", (payload) => {
    cy.makeUserviaAPI(payload)
    .then((userID) => {
    cy.openUserProfile(userID);
    })
    .then((userID) => {
            return userID;
    })
});

beforeEach(() => {

let uid = cy.createUser("userCreate")
    cy.updpateUser(uid)
});

但是我得到的 userID 为 null 或带有某些 windows 对象。有人可以指导我如何传递返回变量“userID”并在 test.cy.js 中的新函数中将其用作 updateUser(userID) 吗?抱歉,我是 JS 新手,需要指导。 注意:我无法将 updateUser() 移动到 createUser() 内部,因为它们需要彼此独立。 未来还会有多种功能需要 userID 作为主要参数来操作。

javascript cypress ui-automation cypress-custom-commands
1个回答
0
投票

由于您指定了一个规范文件

test.cy.js
,因此可以使用 alias 来包装
userID
的值。

这里我有简单版本的命令来显示值

abc
保留在正确的位置:

Cypress.Commands.add('makeUserviaAPI', () => {
  const userID = 'abc'                           // simple assign and return result
  return userID
})

Cypress.Commands.add('openUserProfile', () => {
                                                 // doing somthing here
})

Cypress.Commands.add("createUser", (payload) => {
  cy.makeUserviaAPI(payload).then((userID) => {
    cy.openUserProfile(userID)
    cy.wrap(userID).as('userID')                 // publish the userID 
  })
})

Cypress.Commands.add('updateUser', (userID) => {
  expect(userID).to.eq('abc')                     // checking - it passes
})

beforeEach(() => {
  cy.createUser("userCreate").then(userID => {
    cy.updateUser(userID)
  })
})

it('test1', () => {
  cy.get('@userID').should('eq', 'abc')          // checking - it passes
})

it('test2', () => {
  cy.get('@userID').should('eq', 'abc')          // checking - it passes
})
© www.soinside.com 2019 - 2024. All rights reserved.