0

I have a lot of 'h2' elements with 'a' inside. All I want is just get all the 'a' in the 'h2'

when I try something like this:

 public function testBreakingNewsH2(){

    $this->url('index.php');

    $h2Elements = $this->byCssSelector('h2')->byCssSelector('a')->text();
    $this->assertEquals('Breaking News', $h2Elements);
}

I get only the first 'a' inside 'h2'. I need to check that all 'h2' links are exists (get all 'h2' elements that contains 'a') I tried something like this:

public function testHomePgaeH2(){

    $this->url('index.php');
    $h2Elements = $this->elements($this->using('css selector')->value('h2'));

    $this->assertContains('Breaking News', $h2Elements);
    $this->assertContains('Analysis', $h2Elements);
    $this->assertContains('Calendar', $h2Elements);
    $this->assertContains('Studies', $h2Elements);

}

this not works, this is the best example that I found for my issue. of course I can try something like this:

$this->assrtRegExp('/xxxx/i', $this->source());

but I want make it clean as possible without taking all the source.

please advise, thanks.

1 Answer 1

1

You get a list of elements by css selector with this code:

$elements = $this->elements($this->using('css selector')->value('h2 a'));
foreach ($elements as $i=>$element){
    echo $element->text() . "\n";
}

If you want to check that all h2 contain a, you can find all elements by css selector h2 and count them then find by h2 a and count again. Then compare. Also you can iterate all h2 a elements and check their urls by array or regexp. It depends on what you want.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. maybe u know how can I check specific link name with assertContains for example I want check if "Breaking News" is a link inside the h2 in my site. the problem is if I put assertEqual into foreach it will failure. when I try ` $this->assertContains('Breaking News', $h2Elements); ` it says: Failed asserting that an array contains 'Breaking News'
Make an array: $titles[] = $element->text(); (in foreach) then do $this->assertContains('Breaking News', $titles);
thanks, I so stupid it amazing I forgot that I can use regular php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.