摩卡测试用例 - 嵌套it()函数kosher?

时间:2015-09-23 20:52:39

标签: javascript node.js asynchronous jasmine mocha

我有这种情况,我想我想在Mocha测试中嵌套`max(N * LDir, 0.0)` 测试用例。我确信这是错的,我没有看到任何建议去做我正在做的事情,但我现在还不知道更好的方法 -

基本上,我有一个“父”测试,在父测试中有一个带有所有“子”测试的forEach循环:

it()

正如你所看到的,两个单独的行被注释掉了 - 我想要包含它们以便我可以很容易地看到每个单独测试的结果,但是我有这种尴尬的情况,在回调旁边和回调一起触发了回调for async.each。

之前有没有人见过这种情况并知道一个好的解决方案,测试人员可以在循环中轻松查看每个测试的结果?

2 个答案:

答案 0 :(得分:6)

不要嵌套it来电。同步调用它们。

嵌套it调用在Mocha中永远不会好。 it调用也不是异步执行的。 ( test 可以是异步的,但你不能异步调用 it。)这是一个简单的测试:

describe("level 1", function () {
    describe("first level 2", function () {
        it("foo", function () {
            console.log("foo");
            it("bar", function () {
                console.log("bar");
            });
        });

        setTimeout(function () {
            it("created async", function () {
                console.log("the asyncly created one");
            });
        }, 500);
    });

    describe("second level 2", function () {
        // Give time to the setTimeout above to trigger.
        it("delayed", function (done) {
            setTimeout(done, 1000);
        });
    });
});

如果你运行它,你将无法获得嵌套测试bar将被忽略,并且异步创建的测试(delayed)也将被忽略。

Mocha没有为这些类型的调用定义语义。当我在编写时使用最新版本的Mocha(2.3.3)运行测试时,它只是忽略了它们。我记得Mocha的早期版本会识别测试,但会将它们附加到错误的describe块。

答案 1 :(得分:3)

我认为动态测试的需求相对普遍(数据驱动的测试?),动态it和测试用例有共同用途。

如果测试可以串行执行,我认为管理测试用例完成会更容易。这样您就不必担心管理嵌套异步done了。由于request是异步的(我假设),您的测试用例仍将主要同时执行。

describe('[test] enrichment', function () {

        var self = this;


        _.each(self.tests, function (json, cb) {

            it('[test] ' + path.basename(json), function (done) {

                var jsonDataForEnrichment = require(json);
                jsonDataForEnrichment.customer.accountnum = "8497404620452729";
                jsonDataForEnrichment.customer.data.accountnum = "8497404620452729";
                var options = {
                    url: self.serverURL + ':' + self.serverPort + '/event',
                    json: true,
                    body: jsonDataForEnrichment,
                    method: 'POST'
                };


               request(options,function (error, response, body) {
                    if (error) {
                        cb(error);

                    }
                    else{
                        assert.equal(response.statusCode, 201, "Error: Response Code");
                        cb(null);
                    }

                    done(); 
                });

            });

        }
    });
相关问题