1

I have a mutation observer function:

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);
            }

My qunit tests are failing with the error 'Expected ';' on line 136 (which is this line: for (var mutation of mutationsList) { However I cannot see where I am missing anything or any incorrect syntax? There are no errors showing in Visual Studio either. Can anyone see if there is an error I am missing with this function that might be causing the unit test failure?

Jordan1993
  • 864
  • 1
  • 10
  • 28

1 Answers1

1

It looks like whatever tool is running these tests doesn't understand ES2015+ syntax. The for-of loop was added in ES2015.

You can switch it to a for loop instead:

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

Or, since the mutation list is an actual array, you can use forEach on it:

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

For more alternatives, check out my answer here, which runs through your various options for looping through arrays — just be sure to ignore the ES2015+ ones.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875