1

由於W3C Notification不適用於PhantomJS,因此我無法將我的代碼覆蓋率提高到100%。我有以下功能:W3C通知覆蓋範圍

function requirespermission(overwrite){ 
    if(overwrite || (typeof Notification !== 'undefined' && Notification.permission === 'granted')) 
    { 
     return true; 
    } 
    else if(!overwrite || typeof Notification !== 'undefined'){ 
     Notification.requestPermission(); 
    } 
    return false; 
} 

和我的測試如下:

it('should be able to get permission', function(){ 
    notificationservice.requirespermission(true); 
}); 

it('should be able to not get permission', function(){ 
    notificationservice.requirespermission(false); 
}); 

,但我無論做什麼,其他的功能的情況覆蓋率保持在2/4(這是有道理的,但我必須執行跨瀏覽器支持的檢查)。我使用以下工具:

  • 噶+茉莉花爲測試
  • 卡瑪覆蓋覆蓋
  • PhantomJS作爲單元測試的瀏覽器
  • 的Cobertura作爲記者
  • (詹金斯作爲CI)

如何獲取else函數以通過代碼覆蓋測試?

回答

1

我通過使用Notify.js的包裝通知來解決此問題。現在的代碼是:

function requirespermission(overwrite){ 
    if(!Notify.needsPermission || overwrite) 
    { 
     return true; 
    } 
    else if(Notify.isSupported()){ 
     Notify.requestPermission(); 
    } 
    return false; 
} 

而且測試:

it('should be able to not get permission', function(){ 
    notificationservice.requirespermission(true); 
}); 

it('should be able to not get permission', function(){ 
    spyOn(Notify, 'isSupported').and.returnValue(true); 
    notificationservice.requirespermission(false); 
}); 

it('should handle not-supported', function(){ 
    spyOn(Notify, 'isSupported').and.returnValue(false); 
    notificationservice.requirespermission(false); 
});