如何对此代码进行单元测试

How to unit test this code

本文关键字:单元测试 代码      更新时间:2023-09-26

我用谷歌搜索了如何进行单元测试,但示例非常简单。 这些示例总是显示返回某些内容的函数或返回某些内容的 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函数中完成的。