我想用 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/