2017-06-01 2 views
1

以下のコードのジャスミンテストを書こうとしています...私のメソッドにJASMINEテストケースを書く方法。イベントリスナーを模擬しようとしている。

refreshCacheIfNewVersionIsAvailable();

//Check if a new cache is available on page load and reload the page to refresh app cache to the newer version of files 
function refreshCacheIfNewVersionIsAvailable() { 
    $window.addEventListener('load', function (e) { 
     $window.applicationCache.addEventListener('updateready', function (e) { 
      if ($window.applicationCache.status == window.applicationCache.UPDATEREADY) { 
       // Manifest changed. Now Browser downloadeds a new app cache. 
       alert(textService.versioning.newVersionMessage); 
       $window.location.reload(true); 
      } else { 
       // Manifest didn't change. Nothing new to server. 
      } 
     }, false); 
    }, false); 
} 
+0

あなたは主に '$ window'の方法をスパイする必要があるようです。 **あなたは何の問題がありますか? – Phil

+0

メソッドのSPYの書き方を理解できません。 spyOn(ウィンドウ、 'addEventListener')。and.callFake(function(){ return; }); – Varuna

答えて

1

あなたの挑戦

私はあなたが直面している課題は、あなたがコールバック関数でコードをテストする方法を見ることができないことであると仮定します。テスト中のサービスでスパイが実行された後に、addEventListenerを偵察するときにコールバック関数にアクセスできることを認識するだけで済みます(refreshCacheIfNewVersionIsAvailable)。参照を取得できるので、テストしていた関数と同じように実行することができます。

のサンプル溶液

次は、テストされていない私の頭の上をオフに書かれていますが、私はそのコードをテストしなければならなかった場合の書き込みに期待するものの線に沿って何か。

describe('refreshCacheIfNewVersionIsAvailable()', function() { 
    beforeEach(function() { 
    spyOn($window, 'addEventListener'); 
    }); 

    it('should register a load event handler on the window', function() {  
    refreshCacheIfNewVersionIsAvailable(); 

    expect($window.addEventListener.calls.count()).toBe(1); 

    var args = $window.addEventListener.calls.argsFor(0); 
    expect(args.length).toBe(3); 
    expect(args[0]).toBe('load'); 
    expect(typeof args[1]).toBe('function'); 
    expect(args[2]).toBe(false); 
    }); 

    describe('load event', function() { 
    var loadFunction; 

    beforeEach(function() { 
     refreshCacheIfNewVersionIsAvailable(); 
     var args = $window.addEventListener.calls.argsFor(0); 
     loadFunction = args[1]; 

     spyOn($window.applicationCache, 'addEventListener'); 
    }); 

    it('should register an updateready event handler in the window application cache', function() { 
     loadFunction(); 

     expect($window.applicationCache.addEventListener.calls.count()).toBe(1); 

     var args = $window.applicationCache.addEventListener.calls.argsFor(0); 
     expect(args.length).toBe(3); 
     expect(args[0]).toBe('updateReady'); 
     expect(typeof args[1]).toBe('function'); 
     expect(args[2]).toBe(false); 
    }); 

    describe('updateready event', function() { 
     var updateReadyFunction; 

     beforeEach(function() { 
     loadFunction(); 
     var args = $window.applicationCache.addEventListener.calls.argsFor(0); 
     updateReadyFunction = args[1]; 
     }); 

     it('should reload the window if the status is UPDATEREADY', function() { 
     // You get the point 
     }); 
    }); 
    }); 
}); 
関連する問題