如何避免在nodejs测试中进行深度嵌套?

时间:2013-11-18 14:57:52

标签: javascript node.js closures mocha

你会介意分享测试nodejs的最佳实践吗?

为避免深度筑巢,您有什么经验?在编写测试时无法弄清楚如何将此代码重构为闭包。

describe('ProcessRawData', function(){
  describe('event that has been already handled', function(){
    beforeEach(function(done){
      store.testMode(true);
      var filename = __dirname + '/data/test.txt';
      fs.readFile(filename, 'utf8', function(err, rawData) {
        prd.process(rawData, function(err, data){
        var rawMsgSha1 = '123464fbcb34c333f4300a88f019f43e7de757d6'; 
        store.sismember('events:handled', rawMsgSha1, function(err, exists){
          if (err) throw err;
          assert.ok(exists);
          done();
      });
    });
  });
})

1 个答案:

答案 0 :(得分:3)

您可以考虑使用像step这样的异步流量控制库,这会使您的代码看起来像这样(未经测试):

describe('ProcessRawData', function(){
  describe('event that has been already handled', function(){
    beforeEach(function(done){
      store.testMode(true);
      var filename = __dirname + '/data/test.txt';

      Step(
        function readFile() {
          fs.readFile(filename, 'utf8', this);
        },
        function processRawData(err, rawData) {
          if (err) throw err;
          prd.process(rawData, this);
        },
        function doMoreProcessing(err, data) {
          if (err) throw err;
          var rawMsgSha1 = '123464fbcb34c333f4300a88f019f43e7de757d6';
          store.sismember('events:handled', rawMsgSha1, this);
        },
        function checkIfExists(err, exists) {
          if (err) throw err;
          assert.ok(exists);
          done();
        }
      );
    });
  });
})