javascript 比较Cypress中元素的值

nvbavucw  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(139)

考虑下面两个DOM结构元素

<li
  class="facet sector multiselect selected"
  data-bind="click: function(data, e) { $parent.sectors.setParentSector.call($parent, data, e); }, attr: { 'class' : 'facet sector multiselect' + (Selected() ? ' selected' : '') + (Disabled() ? ' disabled' : '')}"
>
  <a
    href="***parentsector=financial-services"
    data-bind="text: SectorName(), attr: { href: Url() }"
    >Financial Services</a
  >
  <span class="count" data-bind="text: '(' + JobCount() + ')'">(62)</span>
</li>
<div class="col-md-12">
  <div class="page-counter">1 - 25 of 62 jobs</div>
</div>

我的要求是验证来自第一个元素的count(62)等于页面计数器元素(1 - 25 of 62)中出现的作业总数。
我使用了这个解决方案,但它没有工作:

it("Verify job count of filter applied should be equal to total jobs appear in webpage  ", () => {
  let count;

  cy.searchKeyword(fdata); //ignore this code as it is not relevant to this context.

  cy.get(":nth-child(7) > .count").click();
  cy.get(".selected > .count").then(($el) => {
    count = $el.text;
    cy.log(count);
  });

  cy.get(":nth-child(1) > .row-top > .row > .col-md-12 > .page-counter")
    .contains("${count}")
    .should("be.true");
});

让我知道我的逻辑哪里不正确

ujv3wf0j

ujv3wf0j1#

看起来不错,除了几件事

  • .contains("${count}")看起来像是你在尝试使用字符串模板,但是需要在它周围加上反引号,所以它会在页面计数器中查找${}。你可以只使用.contains(count),但是哪个数字是正确的比较-25还是62
  • 在最后的检查中,count变量的值仍然是undefined,因为你过早地使用了它。要么在最后一条语句周围添加另一个.then(),要么将计数传递到链的下面,而不是使用外部变量。

这里有一些代码,可能会更好

count变量的延迟使用

it("Verify job count ...", () => {
  let count;

  cy.searchKeyword(fdata); //ignore this code as it is not relevant to this context.

  cy.get(":nth-child(7) > .count").click();
  cy.get(".selected > .count").then(($el) => {

    count = $el.text()  // extract text
    cy.log(count);
  })
  .then(() => {

    // this nesting delays use of count variable until it has been set

    cy.get(":nth-child(1) > .row-top > .row > .col-md-12 > .page-counter")
      .invoke('text')
      .then(counterText => {

        expect(counterText).to.eq(`1 - 25 of ${count} jobs`)
        // or
        expect(counterText).to.eq(`1 - ${count} of 62 jobs`)
      })
  })
})

向下传递计数

it("Verify job count ...", () => {

  cy.searchKeyword(fdata); //ignore this code as it is not relevant to this context.

  cy.get(":nth-child(7) > .count").click();
  cy.get(".selected > .count").then(($el) => {

    count = $el.text()  // extract text
    cy.log(count);
    return count
  })
  .then(count => {

    // passing in the count from previous command
    // so don't have to worry about using the external variable
    // too early

    cy.get(":nth-child(1) > .row-top > .row > .col-md-12 > .page-counter")
      .invoke('text')
      .then(counterText => {

        expect(counterText).to.eq(`1 - 25 of ${count} jobs`)
        // or
        expect(counterText).to.eq(`1 - ${count} of 62 jobs`)
      })
  })
})

相关问题