node.js - 我如何用 mocha 排除常见的 before() 调用?

标签 node.js mocha.js

我的 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);
});

如果我忘记调用 beforeEach ,这可能会导致问题,重构起来会很痛苦。我想定义一个 describe 确保我总是调用我的设置和拆卸,所以我可以写:

我想这样写:

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

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

我该怎么做,因为 mocha 将 describe 定义为全局的?如何确保一切都按正确的顺序执行?

最佳答案

我会创建一个包含以下内容的 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;

然后我可以拥有 test/something.js:

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

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

test/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)

关于node.js - 我如何用 mocha 排除常见的 before() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29312331/

相关文章:

javascript - 如何过滤包含给定字符串但也可能包含其他字符串的 airtable 记录?

html - 使用 Express.js 提供纯文本 SVG(与 Cheerio.js 相关的解决方案)

javascript - 在使用 mocha 的测试脚本中从 webhook 接收通知事件

javascript - Chai deep.include 抛出错误 "Uncaught AssertionError: expected..."

node.js - 返回的 GeoFire 结果不按距离排序

javascript - 我可以为 HTML5 文件上传设置视频长度限制吗?

node.js - Express,Handlebars 显示 flash 信息

javascript - 如何在 Vue 中测试组件是否发出事件?

ruby-on-rails - 使用 rspec 确保记录器被调用

node.js - 如何访问和测试 node.js 模块中的内部(非导出)函数?