首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中进行单元测试时重用代码的最佳方法

在javascript中进行单元测试时重用代码的最佳方法
EN

Stack Overflow用户
提问于 2016-02-06 19:36:23
回答 2查看 384关注 0票数 1

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

代码语言:javascript
复制
// Test globals
var var1='foo1', var2='foo2';

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

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

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

EN

回答 2

Stack Overflow用户

发布于 2016-02-06 19:44:42

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

代码语言:javascript
复制
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   }
        }
     ]
  }
}

测试看起来是这样的:

代码语言:javascript
复制
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))
})
票数 0
EN

Stack Overflow用户

发布于 2016-02-06 22:09:01

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

我会做这样的事情

代码语言:javascript
复制
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();

现在我们可以更进一步,让这个类的模板也是可定制的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35240539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档