gpt4 book ai didi

javascript - 如何对这段代码进行单元测试

转载 作者:行者123 更新时间:2023-11-29 22:25:01 25 4
gpt4 key购买 nike

我在谷歌上搜索了如何进行单元测试,但示例非常简单。这些示例总是显示返回某些东西的函数或执行返回某些东西的 ajax - 但我从未见过执行回调、嵌套回调和“单向”函数的示例,它们只是存储一些东西而不返回任何东西。

假设我有这样的代码,我应该如何测试它?

(function(){
var cache = {};

function dependencyLoader(dependencies,callback2){
//loads a script to the page, and notes it in the cache
if(allLoaded){
callback2()
}
}

function moduleLoader(dependencies, callback1){
dependencyLoader(dependencies,function(){
//do some setup
callback1()
});
}

window.framework = {
moduleLoader : moduleLoader
}

}());


framework.moduleLoader(['foo','bar','baz'],function(){
//call when all is loaded
})

最佳答案

这说明了在 javascript 的匿名函数中保持私有(private)的问题。验证内部是否正常工作有点困难。

如果首先完成测试,那么缓存、dependencyLoader 和 moduleLoader 应该在框架对象上公开可用。否则将很难验证缓存是否已正确处理。

为了让事情顺利进行,我建议您查看 BDD ,它方便地为您提供了一种方法来帮助您开始,让您使用 given-when-then 约定来阐明行为。我喜欢用 Jasmine ,这是一个 javascript BDD 框架(与 jstestdriver 集成),对于这种事情和我为上面的示例所做的单元测试将是:

describe('given the moduleloader is clear', function() {

beforeEach(function() {
// clear cache
// remove script tag
});

describe('when one dependency is loaded', function() {

beforeEach(function() {
// load a dependency
});

it('then should be in cache', function() {
// check the cache
});

it('then should be in a script tag', function() {
// check the script tag
});

describe('when the same dependency is loaded', function() {

beforeEach(function () {
// attempt to load the same dependency again
});

it('then should only occur once in cache', function() {
// validate it only occurs once in the cache
});

it('then should only occur once in script tag', function() {
// validate it only occurs once in the script tag
});

});
});

// I let the exercise of writing tests for loading multiple modules to the OP

});

希望这些测试是不言自明的。我倾向于重写测试,以便它们很好地嵌套,通常实际调用在 beforeEach 函数中完成,而验证在 it 函数中完成。

关于javascript - 如何对这段代码进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10068335/

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