php - Laravel 测试页面上元素的顺序

标签 php css laravel testing selector

我想用 Laravel TestCase 测试我的排序是否正常工作。我有一个简单的测试页面:

<div id="values">
    @foreach(['Value1', 'Value2'] as $value)
        <div class="test-class">{{$value}}</div>
    @endforeach
</div>

现在我想测试第一个 .test-class 元素是否包含 'Value1'。我尝试了不同的方法,但没有成功。这是第一个:

 public function testSorting()
{
    $this->visit(route('dummy'));
    $this->see('Value1');
    $this->seeInElement('.test-class:first-of-type', 'Value2');
}

这个导致异常:

Symfony\Component\CssSelector\Exception\ExpressionErrorException: "*:first-of-type" is not implemented.

然后我试了一下

$this->seeInElement('#values:first-child', 'Value2');

我的测试是绿色的。但它应该是红色的,因为第一个 child 是'Value1'。它完全忽略了':first-child' 部分。

然后我试了一下

$this->seeInElement('#values:nth-child(1)', 'Value2');

也变绿了。所以这个方法也行不通。

我错过了什么吗?或者无法使用 Laravel 测试来测试页面上元素的顺序?

最佳答案

我来晚了,但我一直在使用下面的命令来检查页面上元素的顺序。到目前为止似乎效果很好。

在您的 TestCase 基类上实现以下方法。

/**
 * Given a CSS selector string, check if the elements matching the query
 * contain the values provided, in the order they are provided.
 *
 * @param string $selector
 * @param array $contents
 * @return $this
 */
public function seeInOrder($selector, Array $contents)
{
    $matches = $this->crawler->filter($selector);

    try {
        foreach ($matches as $index => $domElement) {
            $needle = $contents[$index];
            $this->assertContains($needle, trim($domElement->textContent));
        }
    } catch (PHPUnit_Framework_ExpectationFailedException $e) {
        $this->fail('Failed asserting that the element at index ' . $index . ' contains the string "' . $contents[$index] . '"');
    }

    return $this;
}

用法:

/**
 * Test that the /books route returns a list of books in explicit order.
 *
 * @test
 * @return void
 */
public function books_index_page_lists_books_in_explicit_order()
{
    $book_1 = factory(App\Book::class)->create([
        'order' => 0
    ]);

    $book_2 = factory(App\Book::class)->create([
        'order' => 1
    ]);

    $this->visit('/books')
        ->see($book_1->title)
        ->see($book_2->title)
        ->seeInOrder('.books .book', [
            $book_1->title,
            $book_2->title
        ]);
}

关于php - Laravel 测试页面上元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42999200/

相关文章:

php - 如何使用连接从第 3 级表中获取数据 [Laravel]

css - 新闻 |内容区域不会自动展开

javascript - Div在asp.net中显示无/隐藏javascript函数

php - Laravel 数据库显示为未配置?

php - get_browser 减慢页面加载速度,还有其他选择吗?

php - 非法字符串偏移 'name' laravel

php - 如何从php中搜索mysql

javascript - 平滑地停止 CSS 旋转动画

php - 是否可以在 Laravel asset() 函数中添加 cdn.mydomain.com/assets ?

php - 如何根据 Laravel 中更新的模型自动更新迁移文件