2017-02-21 106 views
-1

在學習電子時,我決定也想在JavaScript中訓練測試技術。我有下面的代碼:摩卡/ Sinon - JavaScript中的單元測試承諾

const winston = require('winston'); 
const AutoLaunch = require('auto-launch'); 

const launchFunction = (mb) => { 
    const autolaunch = new AutoLaunch(); 

    autolaunch 
    .isEnabled() 
    .then((isEnabled) => { 
     if (isEnabled) { 
     return; 
     } 
     autolaunch.enable(); 
    }) 
    .catch((err) => { 
     winston.error(err); 
    }); 
}; 

我想如果斷言autolaunch.enabled()正確特定條件下觸發,我有很多的問題需要編寫任何測試,不會逼我創造存根與然後()函數的確切副本。在這個解決方案的設計中有一個選項可能是錯誤的 - 我可以(並且想要)更改代碼以使其更具可測試性。我應該如何處理這個問題而不影響代碼可測試性?

我用摩卡興農,但我不覺得真正連接到這些工具

+1

請看[chai-as-promised](http://chaijs.com/plugins/chai-as-promised/)來測試承諾。 –

回答

0

我會嘗試更多的功能的方法。功能中封閉問題並單獨測試。

function enableWhenNeeded(autolaunch, isEnabled) { 
     if (isEnabled) { 
     return; 
     } 
     autolaunch.enable(); 
} 

autolaunch 
    .isEnabled() 
    .then(curry(enableWhenNeeded, autolaunch)) 
    .catch((err) => { 
     winston.error(err); 
    }); 

對於這個例子的目的,我提出了功能咖喱(),但我認爲至少有35個它們提供一個JavaScript框架。

這總是一個問題是這個代碼值得測試;如果AutoLaunch是第三方,爲什麼要測試它?