变异观察者单元测试失败,但我不知道为什么

时间:2020-02-27 10:52:20

标签: javascript unit-testing dom

我有一个突变观察者功能:

function trackItemsSelected(elementId, Event) {
                const targetNode = document.getElementById(elementId);
                const config = { attributes: true, childList: true, subtree: true };
                var removedItemCount = 0;

                const callback = function (mutationsList) {
                    for (var mutation of mutationsList) {
                        if (mutation.type === 'childList') {
                            Event("item added");
                        }
                        if (mutation.type === 'attributes') {
                            removedItemCount += 1;
                        }
                    }
                    if (removedItemCount > 0) {
                        Event("item removed");
                        removedItemCount = 0;
                    }
                };
                const observer = new MutationObserver(callback);
                observer.observe(targetNode, config);
            }

我的qunit测试失败,错误为'Expected';'。在第136行(此行:for (var mutation of mutationsList) { 上,但是我看不到丢失任何内容或语法不正确的地方吗?Visual Studio中也没有显示错误。任何人都可以查看是否有我遗漏的错误此功能可能导致单元测试失败?

1 个答案:

答案 0 :(得分:1)

似乎所有正在运行这些测试的工具都无法理解ES2015 +语法。在ES2015中添加了for-of循环。

您可以改为将其切换到for循环:

for (var i = 0, len = mutationsList.length; i < len; ++i) {
    var mutation = mutations[i];
    // ...
}

或者,由于变异列表是一个实际的数组,因此可以在其上使用forEach

mutationsList.forEach(function(mutation) {
    // ...
});

有关更多替代方法,请查看my answer here,它遍历了用于循环遍历数组的各种选项-请确保忽略ES2015 +。

相关问题