gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:32:57 24 4
gpt4 key购买 nike

我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com