如何在节点的FileSystem.readfile中unit testing逻辑cb

目前,我有一个读取文件的function。 当我抛出并testingreadfilecallback以外的错误时,它将起作用:

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 }); } 

我的testing:

 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) 

要asynchronous处理错误,可以使用callback或承诺来通知调用者发生错误。

我认为这个问题是:

  • expect(func)被称为
  • readFile产生(因为它是asynchronous的)回到testing
  • testing报告失败

您可以将doWork的调用签名更改为接受callback(传统上将错误作为第一个参数和结果传递)作为第二个参数。


我个人会build议看看承诺,因为我认为他们看起来更清洁,更容易理解/合作。 应该允许你继续抛出,并注册一个catch / error事件来处理exception。

closures@ dm03514,将您的文件读取器逻辑设置为承诺,因为您不能asynchronous直接testing引发。

 // fileprocessor.js 'use strict'; //imports var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); module.exports = class FileProcessor { constructor() { } process(path) { var deferred = Promise.pending(); //like $q.deferred() in angular fs.readFileAsync(path, 'utf8').then(content => { //... etc... logic... etc... if(content.split('\n')[0] > 10) deferred.reject(new RangeError('bad')); //... etc.. more... logic deferred.resolve('good'); }).catch(error => deferred.reject(error)); return deferred.promise; } } 

然后在你的testing套件中。

 //test.js 'use strict'; var chai = require('chai'); var expect = chai.expect; var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var FileProcessor = require('./fileprocessor.js'); describe('my test suite', function(){ var func = () => { return new FileProcessor().process('my path'); } it('should resolve with a value', () => { return expect(func).should.eventually.equal('good'); }); it('should reject with an error', () => { return expect(func).should.be.rejectedWith(RangeError); }); }); 

看看chai-as-promised : http : //chaijs.com/plugins/chai-as-promised/