You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel Dusk断言元素的CSS样式?

在Laravel Dusk中断言元素的实际CSS样式

Laravel Dusk本身没有内置的直接断言元素计算样式的方法,但可以通过执行JavaScript获取元素最终应用的样式,再进行断言。以下是具体实现方案:

基础用法:直接断言背景色

假设你要验证类为.user.invalid的元素背景色是否为红色,可通过window.getComputedStyle获取计算后的样式:

$browser->visit('/your-page-url');

// 获取元素的计算背景色
$backgroundColor = $browser->executeScript("return window.getComputedStyle(document.querySelector('.user.invalid')).backgroundColor;");

// 断言样式值,注意返回值为RGB格式
$this->assertEquals('rgb(255, 0, 0)', $backgroundColor);

扩展:断言其他样式属性

如果需要验证其他样式(比如字体大小、边框),只需修改对应的CSS属性名即可:

// 断言字体大小为16px
$fontSize = $browser->executeScript("return window.getComputedStyle(document.querySelector('.target-element')).fontSize;");
$this->assertEquals('16px', $fontSize);

// 断言边框样式为1px solid #000
$border = $browser->executeScript("return window.getComputedStyle(document.querySelector('.target-element')).border;");
$this->assertEquals('1px solid rgb(0, 0, 0)', $border);

优化:封装自定义断言方法

为了复用代码,可以在DuskTestCase中封装一个自定义断言方法:

protected function assertElementStyle(string $selector, string $property, string $expectedValue)
{
    $actualValue = $this->browse(function ($browser) use ($selector, $property) {
        return $browser->executeScript("return window.getComputedStyle(document.querySelector('{$selector}')).{$property};");
    });

    $this->assertEquals($expectedValue, $actualValue);
}

之后在测试中直接调用:

$this->assertElementStyle('.user.invalid', 'backgroundColor', 'rgb(255, 0, 0)');
$this->assertElementStyle('.target-element', 'fontSize', '16px');

注意事项

  • getComputedStyle返回的样式值格式需要和预期完全匹配,比如颜色通常返回RGB/RGBA格式,而非十六进制;长度单位会包含px等后缀。
  • 确保元素选择器能唯一定位目标元素,避免返回错误的样式值。

内容的提问来源于stack exchange,提问作者Shahab.es

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 04:10:35