2016-09-19 170 views
0

我仍然在學習繩索單元測試角度。我有一個角色服務,用於創建HTML5通知。代碼類似於以下內容:

(function() { 
    'use strict'; 

    angular 
    .module('blah') 
    .factory('OffPageNotification', offPageNotificationFactory); 

    function offPageNotificationFactory($window) { 
    //Request permission for HTML5 notifications as soon as we can 
    if($window.Notification && $window.Notification.permission !== 'denied')  { 
     $window.Notification.requestPermission(function (status) { }); 
    } 

    function OffPageNotification() { 
     var self = Object.create(OffPageNotification.prototype); 
     self.visibleNotification = null; 
     return self; 
    } 


OffPageNotification.prototype.startNotification = function (options) { 
     var self = this; 
     self.options = options; 
     if(self.options.showHtml5Notification && (!self.options.onlyShowIfPageIsHidden || $window.document.hidden)) { 
    if($window.Notification && $window.Notification.permission !== 'denied')  { 
      self.visibleNotification = new $window.Notification('Notification',  { 
       body: self.options.notificationText, 
       icon: self.options.notificationIcon 
      }); 
     } 
     } 
    }; 

    . 
    . 
    . 
    return new OffPageNotification(); 
    } 
})(); 

我試圖寫這個單元測試,但我不確定如何嘲笑$ window.Notification因此它可以作爲兩種構造...

self.visibleNotification = new $window.Notification(....) 

並且還包含屬性

if($window.Notification && $window.Notification.permission !== 'denied') 

和方法....

$window.Notification.requestPermission(

我已經試過的東西的一個例子是:

 describe('startNotification', function() { 

    beforeEach(function() { 
     var mockNotification = function (title, options) { 
     this.title = title; 
     this.options = options; 
     this.requestPermission = sinon.stub(); 
     }; 

     mockNotification.prototype.permission = 'granted'; 

     mockWindow = { 
     Notification: new mockNotification('blah', {}), 
     document: {hidden: true} 
     }; 

     inject(function (_OffPageNotification_) { 
     OffPageNotification = _OffPageNotification_; 
     }); 
    }); 

    it('should display a html5 notification if the relevant value is true in the options, and permission has been granted', function(){ 
     var options = { 
     showHtml5Notification: true, 
     onlyShowIfPageIsHidden: true 
     }; 
     OffPageNotification.startNotification(options); 
    }); 
    }); 

我得到一個錯誤說「$ window.Notification不是構造函數」這一設置,我明白爲什麼(我傳遞的實例化版本模擬通知)。但是,如果我設置mockWindow.Notification = mockNotification,那麼當它調用requestPermission時會得到一個錯誤,因爲這是未定義的。

任何幫助表示讚賞

回答

1

Notification應該是一個構造函數。它應該有靜態propertiesmethods

所有mockNotification的相關屬性都實例屬性,而他們應該是靜態的:

function MockNotification() {} 

MockNotification.title = title; 
MockNotification.options = options; 
MockNotification.requestPermission = sinon.stub(); 

    mockWindow = { 
    Notification: MockNotification, 
    document: {hidden: true} 
    }; 
+0

感謝,得到它在您的幫助工作 – Neil