gpt4 book ai didi

javascript - 在 javascript 中编写单元测试函数的更好方法是什么

转载 作者:行者123 更新时间:2023-12-03 07:05:36 25 4
gpt4 key购买 nike

在 javascript 中,相同的函数可以用不同的方式编写,例如以下。哪种方式最适合单元测试场景

 // 1st way ============ 
var app = {};
app.name = "abc"
app.init = function () {
return "test";
};

// 2nd way ============
function app() {
this.name = "abc";
};
app.prototype.init = function () {
return "test";
};

最佳答案

这都很容易测试:

// 1st way
assert.equal(app.name, 'abc')
assert.equal(app.init(), 'test')

// 2nd way
var appInstance = new app()
assert.equal(appInstance.name, 'abc')
assert.equal(appInstance.init(), 'test')

但是,在“第二种方式”中,应用程序应该大写(因为构造函数应该以大写开头)。

“第一种方法”可能有点难以测试,因为 var app 必须作为全局变量导出,并且很难再次编写可变全局对象的测试(副作用)。

因此我建议使用“第二种方式”,因为您可以通过在 beforeEach 中(重新)调用 ctor 来创建一个干净的测试设置(当使用摩卡):

describe('the app'', function() {
var app
beforeEach(function() {
app = new App()
})

it(...)
it(...)
})

如果您不喜欢原型(prototype),可以采用这种方式来实现同样良好的可测试性

var createApp = function() {
var app = {};
app.name = "abc"
app.init = function () {
return "test";
};
return app;
}

关于javascript - 在 javascript 中编写单元测试函数的更好方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36839588/

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