2

単体テストの方法をグーグルで調べましたが、例はとても簡単です。例は常に何かを返す関数、または何かを返す 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
})
4

1 に答える 1

2

これは、javascriptの無名関数で物事をプライベートに保つことに関する問題を示しています。物事が内部で機能していることを検証するのは少し難しいです。

これが最初にテストされた場合は、キャッシュ、dependencyLoader、およびmoduleLoaderがフレームワークオブジェクトで公開されている必要があります。そうしないと、キャッシュが適切に処理されたことを検証するのが困難になります。

物事を進めるために、BDDgiven-when-thenをざっと見てみることをお勧めします。これは、慣例を使用して動作を詳しく説明することから始めるのに役立つアプローチを便利に提供します。私は、javascript BDDフレームワーク(と統合する)であるJasminejstestdriverをこの種のものに使用するのが好きで、上記のサンプルに対して行う単体テストは次のようになります。

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ます。

于 2012-04-09T02:48:48.937 に答える