如何对此代码进行单元测试
How to unit test this code
我用谷歌搜索了如何进行单元测试,但示例非常简单。 这些示例总是显示返回某些内容的函数或返回某些内容的 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中的匿名函数中保持私有的问题。验证事情在内部是否正常工作有点困难。
如果这是首先测试完成的,那么缓存、依赖加载器和模块加载器应该在框架对象上公开可用。否则,很难验证缓存是否得到了正确处理。
为了让事情顺利进行,我建议您对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
函数中完成的。
相关文章:
- 如何使用KARMA对React JSX ES6代码进行单元测试
- 如何在单元测试中使用此JavaScript代码
- 单元测试Angular自举代码
- 在C#中,我如何对客户端用户交互和javascript(jQuery)代码进行单元测试
- 在单元测试中实现逻辑,以缩短语法并提高测试代码的可重用性
- 如何使用 Jest 编写单元测试,用于 Promise 的代码
- 什么是JavaScript单元测试的代码覆盖率的分支
- 如何对此代码进行单元测试
- 我应该如何对有很多重叠的代码进行单元测试
- 浏览器单元测试的代码覆盖率
- 如何确保Jasmine单元测试中的DRY代码
- 我应该为客户端和服务器代码使用不同的单元测试框架吗
- 单元测试Mootools代码的最佳解决方案
- Jenkins/SonarQube单元测试JavaScript的代码覆盖率
- 使用Jasmine进行单元测试:测试没有看到beforeEach()中的代码's spyOn()
- 如何使用Mocha Chai组织用于单元测试BDD的代码
- JavaScript单元测试变量和代码未封装在函数中
- 如何对动态加载javascript文件的javascript代码进行单元测试
- 单元测试javascript代码风格
- visual studio 2015 -在MSBuild中集成javascript单元测试代码覆盖