Test in loop mocha

后端 未结 1 1920
不思量自难忘°
不思量自难忘° 2021-01-18 09:29

I am trying to use data provider in mocha to write less code

var should = require(\'should\'); 
var assert = require(\'assert\');
var request = require(\'sup         


        
相关标签:
1条回答
  • 2021-01-18 09:39

    Change your for loop to something like this:

    function makeTest(p) {
        it(p.describe, function(done) {
            request(url)
                .post('/user/signin')
                .send(p.body)
                .expect(p.status)
                .expect(function(res) {
                    assert.equal(res.body.code, p.status);
                    assert.equal(res.body.message, p.message);
                })
                .end(done);
        });
    }
    
    for (var i in provider) {
        makeTest(provider[i]);
    }
    

    The problem with the code you have is that you are actually only testing the last element in your array. (Yes, even though you see different test names.) The anonymous function you pass to it will execute at some point in the future, when Mocha gets to it. By that time your loop will have finished executing and the value of i will be the last value that the loop gave to it. It is not a problem for the first argument you give to it because that argument is evaluated right away. This is why the test names are okay but the tests themselves are just multiple instances of testing the last element in your array.

    The code above solves the issue by passing provider[i] to makeTest. When the anonymous function in makeTest then refers to the p that was used when it was created, it has the value that was used when makeTest was called.

    0 讨论(0)
提交回复
热议问题