gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:04 24 4
gpt4 key购买 nike

我使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com