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

Randomising element selection for Cypress tests

目前正在测试本地电影预订网站,我必须在该网站上输入一定数量的选定电影票。此处附加屏幕的屏幕截图 -

用于重现问题的存储库 - https://github.com/zac11/iCinema

  1. 克隆存储库。
  2. 进入 client 目录并执行 npm i
  3. 运行 npm start 来自根目录。
  4. Webapp 将在 localhost:3000
  5. 打开

我希望能够以随机方式输入所选电影的电影票,这样它就可以从四张票中随机选择一个类别,然后输入票号 2

现在我可以通过以这种方式对定位器进行硬编码来填充票证类别 -

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

输入 Junior Ticket 类别的票数。我希望能够在四个类别中的任何一个类别中随机输入票证,而不必对类别定位器进行硬编码。

PS - 存储库包含柏树测试也可以是 运行 使用 npm run test

您可以根据以下内容随机分配类别:

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

我需要对我们的应用程序做同样的事情,所以我想出了一个 custom command 来轻松实现这一点。这是我在 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 });
});