Javascript 使用mocha重用场景

Javascript 使用mocha重用场景,javascript,testing,mocha.js,code-reuse,Javascript,Testing,Mocha.js,Code Reuse,最近我开始使用JS和摩卡咖啡 我已经编写了一些测试,但现在我需要重用已经编写的测试 我已经厌倦了寻找“it”/“descripe”重用,但没有找到有用的东西 有谁有好的榜样吗 谢谢考虑到每个测试只设计用于测试单个功能/单元,通常您希望避免重复使用测试。最好保持每个测试都是自包含的,以最小化测试的依赖性 这就是说,如果您在测试中经常重复某些内容,那么可以在每次测试之前使用,以使内容更加简洁 describe("Something", function() { // declare your

最近我开始使用JS和摩卡咖啡

我已经编写了一些测试,但现在我需要重用已经编写的测试

我已经厌倦了寻找“it”/“descripe”重用,但没有找到有用的东西

有谁有好的榜样吗


谢谢

考虑到每个测试只设计用于测试单个功能/单元,通常您希望避免重复使用测试。最好保持每个测试都是自包含的,以最小化测试的依赖性

这就是说,如果您在测试中经常重复某些内容,那么可以在每次测试之前使用
,以使内容更加简洁

describe("Something", function() {

  // declare your reusable var
  var something;

  // this gets called before each test
  beforeEach(function() {
    something = new Something();
  });

  // use the reusable var in each test
  it("should say hello", function() {
    var msg = something.hello();
    assert.equal(msg, "hello");
  });

  // use it again here...
  it("should say bye", function() {
    var msg = something.bye();
    assert.equal(msg, "bye");
  });

});
您甚至可以在每次之前使用异步

beforeEach(function(done) {
  something = new Something();

  // function that takes a while
  something.init(123, done);
});
考虑到如果您只进行单元测试,就不会发现由于组件之间的集成问题而导致的错误,您必须在某个时候一起测试组件。抛弃摩卡来运行这些测试将是一种耻辱。因此,您可能希望使用mocha运行一系列测试,这些测试遵循相同的一般模式,但在一些小方面有所不同

我发现解决这个问题的方法是动态创建测试函数。看起来是这样的:

describe("foo", function () {
    function makeTest(paramA, paramB, ...) {
        return function () {
            // perform the test on the basis of paramA, paramB, ...
        };
    }

    it("test that foo does bar", makeTest("foo_bar.txt", "foo_bar_expected.txt", ...));
    it("test what when baz, then toto", makeTest("when_baz_toto.txt", "totoplex.txt", ...));
    [...]
});
你可以看到一个真实的例子

请注意,没有任何东西强迫您将makeTest函数置于
description
范围内。如果您有一种测试,您认为它足够通用,可以用于其他人,您可以将它放在一个模块中,然后
需要它