javascript - 在 JavaScript 单元测试中重用代码的最佳方法

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

我使用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 中?

最佳答案

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

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))
})

关于javascript - 在 JavaScript 单元测试中重用代码的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35240539/

相关文章:

node.js - 如何使用点符号查找记录并使用 Mongoose 更新模式中的值

java - 如何为不在设备或模拟器上的 Android 运行单元测试?

javascript - d3.js 简单的 csv 树形图两列

javascript - 使用 selenium chrome 驱动程序运行 javascript 文件

javascript - Amcharts图表光标显示在最后位置

javascript - Angular JS 中的错误在浏览器中显示预览为 {{dish.comment}}?

javascript - util继承于node

JavaScript reduce 不能处理数学函数?

ios - 在 XCTestCase 中对类方法进行单元测试

java - 是否有使用 Hamcrest 'describeMismatch' 功能的 JUnit assertThat 版本?