简体   繁体   中英

Loop through an array that is created in an it block

I am writing a code where my it block generates an array, and I like to loop through it and do some tests in the same describe block. I tried writing that array to a file and access it, but those tests executes first before I write to it. I can't access a outside mocha tests, but I like to know whether there is anyway to do it?

it("test",function(done){
  a=[1,2,3]
})

a.forEach(function(i){
  it("test1",function(done){
   console.log(i)      
  })
})

Wouldn't this work?

it("test",function(done){
    a=[1,2,3]
    a.forEach(function(i){
        it("test1",function(done){
        console.log(i)
    })
})
var x = [];
describe("hello",function () {

it("hello1",function(done){
    x = [1,2,3];
    describe("hello2",function () {
        x.forEach(function(y) {       
            it("hello2"+y, function (done) {
                console.log("the number is " + y)
                done()
            })
        })
    })
    done()
});
});

How about:

describe("My describe", function() {
    let a;

    it("test1", function() {
        a = [1, 2, 3];
    });

    a.forEach(function(i) {
        it("test" + i, function() {
            console.log(i);
        });
    });
});

If your tests are asynchronous, you will need to add the done callback to them. But for this simple example using console.log() , it is not necessary.

--EDIT--

I think the answer is "no, you can't do this". I added some console.log statements to see what was happening:

describe("My describe", function() {
    let a = [1, 2];

    it("First test", function() {
        console.log('First test');
        a = [1, 2, 3];
    });

    a.forEach(function(i) {
        console.log(`forEach ${i}`);
        it("Dynamic test " + i, function() {
            console.log(`Dynamic test ${i}`);
        });
    });
});

And this was the output:

$ mocha
forEach 1
forEach 2


  My describe
First test
    ✓ First test
Dynamic test 1
    ✓ Dynamic test 1
Dynamic test 2
    ✓ Dynamic test 2


  3 passing (7ms)

So, mocha is running the entire describe block and creating the dynamic tests before running any of the it blocks. I don't see how you would be able to generate more dynamic tests from inside an it block, after the tests have started.

Does your array creation have to be inside an it block?

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