2016-09-19 107 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