赛普拉斯测试的随机元素选择

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

目前正在测试一个本地的电影预订网站,我需要输入一定数量的票数来选择电影。这里附上屏幕截图----------------------------------------------------------------。

enter image description here

复制问题的储存库---- https:/github.comzac11iCinema。

  1. 克隆repo。
  2. 进入 client 目录,并做 npm i
  3. 运转 npm start 从根目录打开。
  4. Webapp将在 localhost:3000

我希望能够以随机的方式输入所选电影的电影票,以这样的方式,它随机选择一类票我们的四部电影,并输入票号说2

现在我可以通过对定位器进行硬编码的方式来填充票务类别,具体方法是-。

  cy.get('div.tickets-info > div:nth-child(1) > span > b').type(3,{force:true});

其中输入票数为 Junior Ticket 类别。我希望能够在四个类别中随机输入一个票据,而不必硬编码类别定位器。

PS - 仓库中也包含了cypress测试,可以通过使用 npm run test

javascript cypress e2e-testing
1个回答
1
投票

你可以根据下面的内容来随机选择类别。

const picked = Math.floor(Math.random()*3); // this gives you a random value from 0 - 3;

// using template string literals - we can add that into picked
cy.get(`div.tickets-info > div:nth-child(`${picked}`) > span > b`).type(3, {force: true})

from picked - 你可以有一个与类别相关的元素数组。

const categories = ["Junior", "student", "normal", "senior"]

你也可以有票价的值在 categories 作为对象,然后用它来计算总金额。

const categories = [{
  type: "junior", 
  value: 5
}, {
  type: "student",
  value: 3
}, {
  type: "normal"
  value: 10
}, {
  type: "senior",
  value: 3
}]

你可以说,用挑选出来的值来计算总金额

const value = categories[picked].value * random_amount;
cy.get(".sum-field label:nth-child(1)").should("contain", value) // total

1
投票

我需要对我们的应用程序做同样的事情,所以我想出了一个新的方法。自定义命令 来轻松实现这个目标。下面是我在下面的代码。cypress/support/commands.js:

Cypress.Commands.add('any', { prevSubject: 'element' }, (subject, size = 1) => {
  return cy.wrap(subject).then(elementList => {

    // this line enables me to use this command with either cy.get() or cy.wrap()
    elementList = (elementList.jquery) ? elementList.get() : elementList;

    elementList = Cypress._.sampleSize(elementList, size);
    elementList = (elementList.length > 1) ? elementList : elementList[0];

    return cy.wrap(elementList);
  });
});

我也可以使用自定义日志与 Cypress.log() 在您的自定义命令中。为了清楚起见,我从上面的代码中删除了它。

然后,你可以在你的测试中使用它,就像其他cy命令一样。

cy.get('div.tickets-info > div > span > b').any().type(3,{force:true});

或者如果你需要多个命令,

cy.get('div.tickets-info > div > span > b').any(2).each(element => {
    cy.wrap(element).type(2, { force: true });
});
© www.soinside.com 2019 - 2024. All rights reserved.