2017-10-15 65 views
1

我的快遞服務器會引發一個錯誤,如果有參數缺失(例如,DB URI)。我想在摩卡測試它實際上拋出了錯誤,但我不知道如何讓摩卡能做到這一點。摩卡測試明示啓動

if(!parameters.db) { 
    throw new Error('Please provide a db URI'); 
} 

我有一個測試的設置是這樣的:

it('Throws Error when no db URI provided in production mode', function() { 
    expect(require('../server')).to.throw(); 
    done(); 
}); 

當我快速的應用程序引發錯誤,該錯誤被扔進控制檯和測試失敗(事實上,它並沒有結束)。


我的另一個問題是,如果環境處於生產模式,Express僅檢查參數。我試圖將測試套件中的流程環境設置爲生產環境,但是當我運行它時,NODE_ENV仍然設置爲「測試」。

before(function() { 
    env = process.env; 
    // This doesn't really set the environment when I run the tests. 
    process.env.NODE_ENV = 'production'; 
}); 

回答

1

如果你想測試是不是你的應用程序中處理嘗試包裝你調用一個try/catch,如果沒有拋出的錯誤時返回錯誤的異常。

it('Throws Error when no db URI provided in production mode', function() { 
    let threwError = false; 
    try { 
    // create the server that throws the Error 
    require('../server'); 
    } catch (err) { 
    threwError = true; 
    } 
    expect(threwError, 'Didn\'t throw an error, when DB URI is empty').to.be.true; 
}); 
+0

感謝。解決方案的工作,但我已經更新你的代碼修復了一些不起作用的部分,並使其更簡單(在我看來)。 –

+1

這比較簡單一些,但是你仍然有一個bug - 如果你想在try/catch之外expect()它,你需要在try/catch之外定義'threwError'。 – doublesharp