简体   繁体   中英

How can I use “it” in a for loop in mocha testing

 describe('some test', function() {
  for(i = 0; i < someData.length; i++) {
   it("test scenario "+i, function() {
   assert.deepEqual(someValue, someData[i]);
   });
  }
 });

Having the above code is not printing mutiple pass results. It is printing the below (in green color) in the console.

0 passing (42ms)

All the details are here: https://github.com/mochajs/mocha/issues/3074

Mocha doesn't support such behavior. The two most famous workarounds are:

  • IIFE
  • forEach

I would the forEach to be slightly more elegant, here is the possible solution by Scott Santucci (github), and modified by me for your case:

someData.forEach(function(value, i) {
  it(`test scenario ${i}`, function() {
    assert.deepEqual(testValue, value);
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM