QUnit - a test in a loop, the index is always the same

I am trying to test some code, and for this I need to do some tests in a loop, for example:

for (var i = 1; i <= 5; i++) { QUnit.test('Hello ' + i, (assert) => { console.log(i); assert.ok( 1 == '1', 'Result: ' + i); }); } 

Click here for a working example in jsFiddle

But for some reason, i in the loop (and the result) is always 6 , so this code gives me the output as follows:

 6 6 6 6 6 

What am I doing wrong?

+5
source share
1 answer

Given that QUnit defines all tests before running them, you are a victim of the classic var scope problem - var bound to a function, not a for tag.

What does this mean:
You define your test with a given value for i , but that value will change when the test is actually running.

You have several ways around this:

Create IIFE and define your test inside it

 for (var i = 1; i <= 5; i++) { (function (j) { QUnit.test('Hello ' + j, (assert) => { console.log(j); assert.ok( 1 == '1', 'Result: ' + j); }); })(i); } 

Why it works: the above variable j will be related to the scope of this IIFE. Its value will not change when the test starts.

Use let keyword in ES6

 for (let i = 1; i <= 5; i++) { QUnit.test('Hello ' + i, (assert) => { console.log(i); assert.ok( 1 == '1', 'Result: ' + i); }); } 

Why it works: ES6 finally introduces a scan area , but this is done using the let or const keywords.

some parts of this answer are confirmed here

+4
source

Source: https://habr.com/ru/post/1245116/


All Articles