是否可以在重复的 div 中断言文本?

Is it possible to assert text in a repeated div?

我正在使用 behat/mink 创建一些 BDD 测试。我想知道是否可以在页面中重复的 div 中获取文本。例如:

<div class="message">Text 1</div>
<div class="message">Text 2</div>
<div class="message">Text 3</div>

class重复,但文字不同。我想断言第二个 div.

中显示的文本

http://casperjs.readthedocs.org/en/latest/modules/tester.html

这是一个 javascript 测试 API,允许您断言 dom

中的任何内容

你可以 clean/modify iReadContentOfDiv() 方法,你想怎样就怎样。

小黄瓜

  Scenario: Iterate classes
    Given I am on "about"
    Then I should see "Welcome to About page"
    And The content of repeated ".message" div should be:
      | content |
      | Text 1  |
      | Text 2  |
      | Text 3  |

FeatureContext.php

namespace MyProject\ApiBundle\Features\Context;

use Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;

class FeatureContext extends MinkContext
{

    /**
     * @When /^The content of repeated "([^"]*)" div should be:$/
     */
    public function iReadContentOfDiv($class, TableNode $table)
    {
        $session = $this->getSession();
        $page = $session->getPage();
        $element = $page->findAll('css', $class);

        if (null === $element) {
            throw new \InvalidArgumentException(sprintf('Could not evaluate CSS: "%s"', $class));
        }

        $found = [];
        foreach ($element as $e) {
            $found[] = $e->getText();
        }

        foreach ($table->getHash() as $element) {
            if (!in_array($element['content'], $found)) {
                throw new Exception(sprintf('Data "%s" not found in DOM element "%s".', $element['content'], $class));
            }
        }
    }
}

ABOUT页面内容:

<div class="message">Text 1</div>
<div class="message">Text 2</div>
<div class="message">Text 3</div>

基于@BentCoder的回答,我做了一个小改动来解决问题:

  /**
   * @Then /^The content of repeated "([^"]*)" div should contain "([^"]*)"$/
   */
  public function iReadContentOfDiv($class, $text)
  {
    $session = $this->getSession();
    $page = $session->getPage();
    $element = $page->findAll('css', $class);

    if (null === $element) {
      throw new \InvalidArgumentException(sprintf('Could not evaluate CSS: "%s"', $class));
    }

    foreach ($element as $e) {
      if (strpos($e->getText(), $text)){
        print 'opa';
        return;
      }
    }

    throw new Exception(sprintf('Data "%s" not found in DOM element "%s".', $text, $class));

  }