Bluebird Each loop in Mocha not working

前端 未结 2 1070
深忆病人
深忆病人 2021-01-16 22:59

I am writing a test where I need to loop over the results of an async api call and dynamically make mocha \'Its\' to test each iteration of the response. I found some other

2条回答
  •  长发绾君心
    2021-01-17 00:00

    I think the problem is that you must define the tests synchronously, although each individual test may complete asynchronously. You can dynamically define it() blocks from static data because these tests are defined before the describe() call returns.

    I don't fully understand why the test works asynchronously with little or no timeout interval, but my experiments suggest that it() must be called at least once before describe() returns for tests to be recognized in the output. With a 1 millisecond timeout, I saw tests described in the parent block.

    Using before() blocks suffers from the same problem. before() could wait for the promised array to resolve, but without any it() tests statically defined, before() will never get run.

    The simple but undesirable alternative would be to have a single it() block test all of the data returned by your service. Another would be to use the results of your web service to first dynamically generate a mocha test file, then run mocha against it.

    var assert = require("assert");
    var Promise = require("bluebird");
    
    var testData = [
        { "name": "Test 1", "value": true },
        { "name": "Test 2", "value": false },
        { "name": "Test 3", "value": true }
    ];
    
    function getTestData(timeout) {
        return new Promise(function (resolve, reject) {
            if (timeout) {
                setTimeout(function () {
                    resolve(testData);
                }, timeout);
            } else {
                resolve(testData);
            }
        });
    }
    
    describe("Dynamicly Generating Tests", function() {
    
        describe("A: Promised Array, no timeout - Works", function () {
            getTestData().each(function (test) {
                it("A: " + test.name, function () {
                    assert.ok(test.value);
                });
            });
        });
    
        describe("B: Promised Array, short timeout - Works?", function () {
            getTestData(1).then(function (testData) {
                testData.forEach(function (test) {
                    it("B:" + test.name, function () {
                        assert.ok(test.value);
                    });
                });
            });
        });
    
        describe("C: Promised Array, timeout, single it() - Works!", function () {
            it("C: Has all correct values", function () {
                return getTestData(1000).each(function (test) {
                    assert.ok(test.value, test.name);
                });
            })
        });
    
    });
    

提交回复
热议问题