【问题标题】:Reuse scenarios by using mocha使用 mocha 重用场景
【发布时间】:2013-12-25 10:58:08
【问题描述】:

最近开始使用 JS 和 mocha。

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

我已经厌倦了寻找“它”/“描述”重用,但没有找到有用的东西......

谁有好的例子?

谢谢

【问题讨论】:

    标签: javascript testing mocha.js code-reuse


    【解决方案1】:

    考虑到如果您进行单元测试,您将不会因组件之间的集成问题而捕获错误,因此您有时需要一起测试您的组件。丢掉 mocha 来运行这些测试将是一种耻辱。因此,您可能希望使用 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", ...));
        [...]
    });
    

    你可以看一个真实的例子here

    请注意,没有什么会迫使您将 makeTest 函数置于describe 范围内。如果你有一种测试,你认为它足够通用,对其他人有用,你可以把它放在一个模块中,然后require它。

    【讨论】:

      【解决方案2】:

      考虑到每个测试仅设计用于测试单个功能/单元,通常您希望避免重复使用您的测试。最好让每个测试都保持独立,并尽量减少测试的依赖关系。

      也就是说,如果您在测试中经常重复某些内容,则可以使用 beforeEach 以使事情更简洁

      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

      beforeEach(function(done) {
        something = new Something();
      
        // function that takes a while
        something.init(123, done);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-07
        • 1970-01-01
        • 2021-09-13
        • 2015-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多