gpt4 book ai didi

javascript - 使用 Mocha 测试样式集

转载 作者:行者123 更新时间:2023-11-28 15:31:43 25 4
gpt4 key购买 nike

我正在尝试测试一些“样式集”函数,但我遇到了问题,因为我需要等到元素完全呈现,然后读取它的属性并检查它是否已成功更改。我知道这很明显,但我想知道是否有一种方法无需等待即可完成同样的操作。

比如我要测试这个功能:

function changeWidth() {
document.getElementById('test').style.width = '200px';
}

我在 Mocha 中使用这个测试:

it('Width should be 200px', () => {
changeWidth();
assert.equal(document.getElementById('test').style.width, '200px');
});

该断言将始终返回 false。以下测试将起作用:

it('Width should be 200px', () => {
changeWidth();
window.setTimeout( () => {
assert.equal(document.getElementById('test').style.width, '200px');
}, 1000);
});

在不使用超时的情况下,它必须是完成相同任务的更好方法。有人可以指导我吗?谢谢!

最佳答案

我注意到两件事:

  1. 不,您不能强制渲染同步进行。浏览器决定,所以测试将是异步的并且有点困惑。也就是说,有比 setTimeout(稍微)更优雅的答案。
  2. 您的测试是同步的,而逻辑是异步的。这意味着您的测试将始终通过,因为在测试完成后调用断言(请参阅 this )。您需要将回调传递给测试,以便在测试完成时调用。

您可以使用 requestAnimationFrame 使测试更清晰一些.只需创建一个助手程序,它将在单独的动画帧中运行传递给它的每个函数,您将保证有单独的渲染阶段。

function runSteps(fns) {
if(!fns.length) return;

var current = fns[0];
var rest = fns.slice(1);

requestAnimationFrame(function() {
current();
runSteps(rest);
})
}

// note the `done` argument - it is what makes Mocha able to know
// when the test is finished. See https://stackoverflow.com/questions/20748918/cannot-run-mocha-js-in-synchronous-mode
it('should run dom render steps chronologically', function(done) {
function assertWidthChanged(){
assert.equal(
document.getElementById('test').style.width,
'200px'
);
}

runSteps([
changeWidth,
assertWidthChanged,
done
]);
}

关于javascript - 使用 Mocha 测试样式集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com