Symfony Crawler:如何检查指向特定页面的链接是否存在


Symfony Crawler: how to check that a link to a particular page exists

我正在编写一些功能测试,我想验证如果用户已登录,页面上是否存在"编辑"链接。

该链接是一个简单的<a href="/profile/22/edit">Edit</a>

如何使用Symfony的爬虫组件过滤它?

一种解决方案是这样的:

$this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count());

但是我想改用标签选择,那么我该怎么做呢?

您可以使用 Crawler::filterXPath() 来检查是否存在与各种条件匹配的 html 元素。为了检查链接是否存在,我更喜欢使用元素 id,因为它最有可能保持不变。例如,如果您按如下方式修改链接:

<a id="edit-profile-link" href="/profile/22/edit">Edit</a>

然后,您可以像这样检查链接是否存在:

$node = $crawler->filterXPath('//a[@id="edit-profile-link"]');
$this->assertTrue($node->count() == 1), "Edit profile link exists");

下面是一些可以与 XPath 一起使用的筛选器类型的良好示例。