2012-04-09 2 views
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 
}) 
+1

私は誤植があると思います。それは 'moduleloader:moduleLoader'と言うべきでしょう。さもなければそれは未定義です。これは単体テストで取り上げられたはずです。 :-) – Spoike

+0

@ Spoikeはそれに感謝します。 – Joseph

答えて

2

これは、javascriptの無名関数で物事を非公開にする問題を示しています。物事が内部的に働いていることを検証することは少し難しいです。

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

私がBDDをぶらぶらすることをお勧めします。便宜上、given-when-thenの慣習で振る舞いを説明することから始めることができます。 Iこの種のものとあなたは上記の持っているサンプルのようになりために私が作ると思いますユニットテストのために、(それがjstestdriverと統合)javascriptのBDDフレームワークである、Jasmineを使用したい:

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 

}); 

希望、これらはテストは自明です。私はテストを書き直してうまくいきます。通常、it関数で検証が行われている間に実際の呼び出しはbeforeEachの関数で行われます。

+0

また、ジャスミンの代わりに[mocha](http://visionmedia.github.com/mocha/)を使用してください。私は個人的には経験はありませんが、同様の構成があります。 – Spoike

関連する問題