等待 CSS 属性

Wait for CSS property

我在 Testcafe 会话中检查 CSS 属性时遇到问题。 我在网站上有一个进度条 html:

<div class="progress-bar progress-bar-success"></div>

当操作就绪后,这个进度ba变成了100%的宽度。

<div class="progress-bar progress-bar-success" style="width: 100%;"></div>

在我的代码中,我现在使用行

await t.expect(Selector('.progress-bar.progress-bar-success').getStyleProperty('width')).eql('100%', {timeout: 90000})

但是不行。它一直等待直到等待时间结束。

我在另一个 运行 中使用了类似的功能,我在其中等待使用 CSS 和 RGB 更改项目的颜色,这非常有效。 我认为现在的问题是,该样式在启动时不可用。或者还有其他的可能吗?

出现这个问题是因为根据 docs getStyleProperty 方法 returns 宽度的计算值,这意味着该值以像素为单位返回,而您想要检查以百分比表示的值。

作为解决方案,我建议您使用ClientFunctions机制,它可以让您获得想要的值。

我为您准备了样品:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .bar {
            width: 500px;
            height: 50px;
            border: 1px solid black;
            overflow: hidden;
        }

        .progress {
            height: 100%;
            background-color: black;
        }
    </style>
</head>
<body>
<div class="bar">
    <div class="progress" style="width: 0;"></div>
</div>

<script>
    setInterval(function () {
        var progress = document.querySelector('.progress');

        progress.style.width = Math.min(100, parseInt(progress.style.width) + 1) + '%';
    }, 50);
</script>
</body>
</html>

这里是测试代码:

import { Selector, ClientFunction } from 'testcafe';

fixture `progress`
    .page `index.html`;

const getStyleWidthInPercents = ClientFunction(() => {
    return document.querySelector('.progress').style.width;
});

test('progress', async t => {
    await t.expect(getStyleWidthInPercents()).eql('100%', {timeout: 90000})
});