2017-05-09 58 views
0

我想使用Mocha/Chai/Sinon從我的History類中測試下面的方法,怎麼樣?如何使用Mocha/Chai/Sinon測試NodeJS fs?

/** 
* Load the history from the history file. 
* @return {this} 
*/ 
load() { 
    const file = historyFilePath(); 

    if (!fs.existsSync(file)) { 
    return this; 
    } 

    const json = fs.readFileSync(file, 'utf8'); 
    const data = JSON.parse(json); 

    this.ary = data; 

    return this; 
} 

全班是here

我已經注意到answer取決於rewire,但我想避免額外的依賴性和rewire也與babel不兼容。

+1

您可以使用Sinon ['stubs'](http://sinonjs.org/releases/v2.2.0/stubs/)。 – robertklep

+0

@robertklep我已經注意到了,我只是無法讓它工作。 – maasha

+0

如果您分享的代碼無法使用,那麼人們可以更輕鬆地爲您提供幫助。 – robertklep

回答

0

假設HistoryFile始終具有相同的結構,一種方法是測試您是否獲得具有正確屬性的對象。

例如,如果你的歷史記錄JSON文件想這

{ 
    "History": { 
     "Name": "Test" 
    } 
} 

你可以寫你的摩卡是這樣的:

it('should return a correct object', function() { 
    const loadedObject = historyUtil.load(); 

    expect(loadedObject).to.have.property("History"); 
    expect(loadedObject.History).to.have.property("Name","Test"); 
} 

這個測試應該會失敗,如果:

  1. FS可以找不到/讀取文件
  2. JSON.parse不會得到一個parsa ble字符串
  3. HistoryFile模式會改變,例如,版本更改。
+1

沒錯,但我想存根fs--這是在文件系統無法訪問或通過慢速遠程連接的情況下進行測試的正確方法。 – maasha