【发布时间】:2019-01-21 09:14:41
【问题描述】:
我想等待一个元素在 CSS 属性中具有特定值。
更具体地说,我正在使用 Testcafe 进行一些功能测试,它们应该等到不透明度从 0 增加到 1。
【问题讨论】:
标签: css node.js testing automated-tests testcafe
我想等待一个元素在 CSS 属性中具有特定值。
更具体地说,我正在使用 Testcafe 进行一些功能测试,它们应该等到不透明度从 0 增加到 1。
【问题讨论】:
标签: css node.js testing automated-tests testcafe
为什么不使用标准的 TestCafe Assertion 机制?你可以这样写
const opacity = await selector.getStyleProperty('opacity');
await t.expect(opacity).eql(1, {timeout: 5000})
Timeout 选项通常在 runner 函数中设置,但可以为每个断言单独指定。它会尽快通过,因为条件是真实的,或者会在 5 秒后失败。
【讨论】:
await selector.getStyleProperty('opacity') 将评估并分配当前值,并且不会再用expect 评估它
const opacity = await selector.getStyleProperty('opacity');// At this point opacity is already equal to a number e.g. 0// It's not a selector that can be evaluated by eql again to change the valueawait t.expect(opacity).eql(1, {timeout: 5000});
await t.expect(selector.getStyleProperty('opacity')).eql(1, {timeout: 5000}) 或 const opacity = selector.getStyleProperty('opacity'); 和 await t.expect(opacity).eql(1, {timeout: 5000})
我想出了这个解决方案,它似乎按我的预期工作。
async waitForOpacity(selector, options) {
const settings = Object.assign(
{
timeout: 30000,
checkInterval: 300,
},
options
);
return new Promise((resolve, reject) => {
let passedTime = 0;
const intervalVisible = setInterval(async () => {
const visible = await selector.visible;
const opacity = await selector.getStyleProperty('opacity');
passedTime = passedTime + settings.checkInterval;
if (visible && opacity > 0) {
clearInterval(intervalVisible);
return resolve();
}
if (passedTime >= settings.timeout) {
clearInterval(intervalVisible);
return reject(new Error('Element did not become visible'));
}
}, settings.checkInterval);
});
}
【讨论】:
遵循锻炼解决方案,其中有一些解释代码的 cmets。
有关 MutationObserver 工作原理的更多信息,您可以查看here。
var observer = new MutationObserver((mutations) => {
//When style property change, this function will be called
mutations.forEach((mutationRecord) => {
//YOU SHOULD IMPLEMENT YOUR <<BUSINESS CODE>> IN HERE
//Then, i check the value of the opacity and see if is equals to 0
if($(myTest).css('opacity') == 1)
console.log("opacity changed");
});
});
//Element that will be the target of the observable
var target = document.getElementById('myTest');
observer.observe(target, {
attributes : true,
attributeFilter : ['style']
}
);
/*Simulates the opacity change on an element*/
setTimeout(() => $(myTest).css('opacity',1), 2000)
#myTest{
opacity:0;
width:30px;
height:30px;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTest"></div>
【讨论】: