0

Below is the simple jest test block in JavaScript, under the describe I've written a simple test to print the current index of the loop (until 5) of which it is put in. But the result is always Test 5

describe("Hello", async ()=>{
    for(var i=0; i<5; ++i){
        test(``Test ${i}``, async ()=>{
            await console.debug("Test "+ i);
        });
    }
});

Can someone please clarify, how does it work?

Canta
  • 1,480
  • 1
  • 13
  • 26
  • generally this is because your `for` finishes before... and then `async` takes the value of `i` after that... you need to pass `i` to `async` function as a parameter. – Flash Thunder Aug 23 '18 at 10:23

1 Answers1

-1

Use let instead of var, let will preserve the scope for each async call. So in each loop, new values of i will be passed to your method and those values will stay preserved. In the case of var the variable i will be function scoped (that function being the one you use as callback in describe()) so when your asyn method resolves, you will see the value of i which exists inside your callback, since the loop would already have ended the value would be 5.

for(let i=0; i<5; ++i){
       // dummy async method
       setTimeout(() => {
          console.log(i)
       }, 2000)
    }
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • @FlashThunder: I don't understand, how?? I know, we can definitely pass the value of `i` to each `function` call but if I pass a block scoped variable in each loop won't the variable's value stay preserved even if loop finishes?? – Ashish Ranjan Aug 23 '18 at 10:55
  • @FlashThunder: I didn't change the meaning after edit, I just elaborated my original answer – Ashish Ranjan Aug 23 '18 at 11:00
  • I remove all my comments and quit. Probably didn't notice the "dummy" method. – Flash Thunder Aug 23 '18 at 11:04