当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 如何使用mocha分解常见的before()调用?

来源:互联网 收集:自由互联 发布时间:2021-06-16
我的mocha测试中有很多重复: describe("Some test", function() { before(helpers.testPrepare); beforeEach(helpers.freshDB); it("should foo", function(done) { //... done(); }); after(helpers.teardownServer);});describe("Another test"
我的mocha测试中有很多重复:

describe("Some test", function() {
    before(helpers.testPrepare);
    beforeEach(helpers.freshDB);

    it("should foo", function(done) {
        //...
        done();
    });

    after(helpers.teardownServer);
});

describe("Another test", function() {
    before(helpers.testPrepare);
    beforeEach(helpers.freshDB);

    it("should bar", function(done) {
        //...
        done();
    });

    after(helpers.teardownServer);
});

如果我忘记在每次调用之前调用它会导致问题,这可能会导致问题.我想定义一个描述,确保我总是调用我的设置和拆解,所以我可以写:

我想把它写成:

var describe = require('./helpers').describe;

describe("Some test", function() {
    it("should foo", function(done) {
        //...
        done();
    });
});

我怎么能这样做,因为摩卡定义描述为全局?如何确保一切按正确的顺序执行?

我会创建一个包含以下内容的helpers.js文件:

function beforeEachExample() { console.log("before each"); }

function beforeExample() { console.log("before"); }

function afterExample() { console.log("after"); }

function makeSuite(desc, cb) {
    describe(desc, function () {
        before(beforeExample);
        beforeEach(beforeEachExample);

        cb();

        after(afterExample);
    });
}

exports.makeSuite = makeSuite;

然后我可以测试/ something.js:

var makeSuite = require("../helpers").makeSuite;

makeSuite("something", function () {
    it("one", function () {});
    it("two", function () {});
});

并测试/ somethingelse.js:

var makeSuite = require("../helpers").makeSuite;

makeSuite("something else", function () {
    it("one", function () {});
    it("two", function () {});
});

运行上面的设置给出:

$mocha

  something
before
before each
    ✓ one 
before each
    ✓ two 
after

  something else
before
before each
    ✓ one 
before each
    ✓ two 
after

  4 passing (5ms)
网友评论