如何使用 Cypress 从 div 中提取文本内容?

5 javascript end-to-end cypress

我想从类名为 的 div 中获取文本.inventory_item_name。HTML 看起来像这样:

<div class="inventory_item_name">Backpack</div>
Run Code Online (Sandbox Code Playgroud)

我的JS代码如下:

const article = cy.get('.inventory_item_price').then((theElement) => {
  theElement.text();
});
Run Code Online (Sandbox Code Playgroud)

问题:当我这样做时,cy.log(article)我得到Object{5}

kon*_*oya 9

就像 Alex 在评论中提到的那样,您不能从命令返回值cy。但你可以在块中这样做,.then就像:

it("should have text of 'Backpack'", () => {
  // I have changed the selector since the class name in your HTML is ".inventory_item_name" not ".inventory_item_price"
  cy.get('.inventory_item_name').then(($el) => {
    const text = $el.text(); // Now you have the text "Backpack"

    // Do the assertion here
    expect(text).to.eq('Backpack');
  });
});
Run Code Online (Sandbox Code Playgroud)

您可以在本文档中详细了解 Cypress 不返回值的原因


Sri*_*odi -1

您可以使用以下代码返回文章文本。另请查看我分享答案的链接以了解更多详细信息。

在链接器方法之外将元素的文本存储在 Cypress 中

return cy.get('.inventory_item_price').then((theElement) => {
      return theElement.text();
    }).then(article => {
      cy.log(`article is ${article}`);
    })
Run Code Online (Sandbox Code Playgroud)