目前,我有一個讀取文件的函數。當我把與測試錯誤的ReadFile的回調之外,它的工作原理:如何在節點的FileSystem.readfile內部單元測試邏輯cb
var doWork = function(path) {
//throw new RangeError('blah'); // works, error is thrown
fs.readFile(path, 'utf-8', function(error, data) {
//etc.... logic.. etc..
if(data.split('\n')[0] > x)
throw new RangeError('blah'); //does not work
});
}
我的測試:
describe('my test suite', function(){
it('should throw an error', function(){
var func = function() {
doWork('my path');
}
var err = new RangeError('blah');
expect(func).to.throw(err); //no error is thrown if "throw" is inside readFile cb
});
});
結果:
AssertionError: expected [Function: func] to throw RangeError
at Context.<anonymous> (test.js:53:27)
https://www.joyent.com/node-js/production/design/errors – dm03514