簡體   English   中英

如何使用Mocha / Chai / Sinon測試NodeJS fs?

[英]How to test NodeJS fs using Mocha/Chai/Sinon?

我想使用Mocha / Chai / Sinon從我的History類中測試以下方法,如何?

/**
 * 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;
}

全班在這里

我已經注意到答案取決於重新布線,但是我想避免額外的依賴性,並且重新布線也與babel不兼容。

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

例如,如果您的History 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沒有獲得可分析的字符串
  3. HistoryFile模式將更改,例如版本更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM