【问题标题】:Best way to reuse code at unit testing in javascript在 javascript 中的单元测试中重用代码的最佳方法
【发布时间】:2016-05-16 09:32:37
【问题描述】:

我使用 buster.js 作为测试运行器。基本测试是这样的:

// Test globals
var var1='foo1', var2='foo2';

// Test run
describe('Description', function(){
    beforeEach(){
        console.log('var2');
    }
    it('should ....', function(){
        expect(var1).toEqual('foo1');
    }
});

现在,假设我有另一个测试需要使用相同的 beforeEach,再加上其他任何东西,以及相同的 it,再加上其他任何东西。

在 JavaScript 中重用此代码的最佳方法是什么?特别是在 buster.js 或 mocha 中?

【问题讨论】:

  • 所以基本上,你想像模板一样使用它吗?
  • 是的,我想,有些想法?

标签: javascript node.js unit-testing mocha.js code-reuse


【解决方案1】:

您需要创建某种上下文并将其封装为一个类。

class TestContext {
   this.var1 = undefined
   this.var2 = undefined

   buildUp(next) {
         // do whatever init you need
        next && next()
   }

  tearDown(next) {
        //clean up stuff
        next && next()
  }

  get sharedTestSteps() {
     return [
        {
            text: "it should something", 
            fn: next => { //...do some testing   }
        }
     ]
  }
}

测试看起来像这样:

describe("...", () => {

   var c = new TextContext()

   before(next => c.buildUp(next))

   after( () => c.tearDown())

   it("should work", () => {
        //work with c.var1
   })

  c.sharedSteps.forEach({text, fn} =>  it(text, fn))
})

【讨论】:

  • 谢谢 Peter,但我不太了解 '=>' 部分和 'next && next()' 部分,是 ES 6 吗?
  • 在我看来像 C#'slinq
  • => 被称为 [fat] 箭头函数运算符。它是一个简写函数定义(具有词法范围的this):a => bfunction(a){return(b);}
  • next && next();if (next != null) next();,也就是说,如果 next 指向某个东西(可能是一个函数),则调用该函数。
【解决方案2】:

这可以使用模板设计模式解决

我会做这样的事情

function TestModule(description){

  this.stages = [];
  this.description = description;
  this.stage = function(name, fn){

    this.stages.push({
      name: name,
      fn: fn
    });

  };

  this.execute = function(){

    describe(this.description, function(){

      //here comes your template
      //this is the part where you define your template
      beforeEach(this.stages[0].fn);
      it(this.stages[1].name, this.stages[1].fn);
      it(this.stages[2].name, this.stages[2].fn);


    });

  };

}


//now this is how you'll use it
var mod = new TestModule('Module description here');

mod.stage('Before each', function(){
  //before each here
});
mod.stage('Should do something', function(){
  //test here
});

mod.execute();

/////////////////////////

//another module

var mod2 = new TestModule('Module description here');

mod2.stage('Before each', function(){
  //before each here
});
mod2.stage('Should do something', function(){
  //test here
});

mod2.execute();

现在我们实际上可以更进一步,使这个类的模板也可以自定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2010-09-27
    相关资源
    最近更新 更多