2017-05-09 56 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