我使用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,加上其他任何东西,同样的它,加上任何其他东西。
在JavaScript中重用这些代码的最佳方法是什么?特别是在buster.js或mocha?
发布于 2016-02-06 19:44:42
这是您需要创建的某种上下文,并将其封装为一个类。
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))
})发布于 2016-02-06 22:09:01
这可以使用模板设计模式来解决
我会做这样的事情
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();现在我们可以更进一步,让这个类的模板也是可定制的。
https://stackoverflow.com/questions/35240539
复制相似问题