node-modules / mm

An simple but flexible mock(or say stub) package, mock mate
Other
158 stars 16 forks source link

测试修复 #34

Open iyuq opened 7 years ago

iyuq commented 7 years ago

测试用例

it.skip('should mock ' + modName + '.request({url: "/bar/foo"}) with stream 500ms response delay',
      function(done) {
        const mockResData = new ChunkStream([ 'mock data with regex url', '哈哈' ]);
        const mockResHeaders = { server: 'mock server' };
        mm[modName].request({ url: '/bar/foo' }, mockResData, mockResHeaders, 500);

        const start = Date.now();
        mod.get({
          host: 'npmjs.org',
          path: '/bar/foo',
        }, function(res) {
          res.headers.should.eql(mockResHeaders);
          res.setEncoding('utf8');
          let body = '';
          res.on('data', function(chunk) {
            chunk.should.be.a.String;
            body += chunk;
          });
          res.on('end', function() {
            const use = Date.now() - start;
            body.should.equal([ 'mock data with regex url', '哈哈' ].join(''));
            use.should.above(490);
            done();
          });
        });
      });

可以修复,问题出在chunkstream模块上,node.js升级后stream只有在接受到stream.push(null);的数据后才可以触发end事件,我有两个修改方案,都是将chunkstream作修改, 方案一:

'use strict';

/**
 * Module dependencies.
 */

var Readable = require('stream').Readable;
var util = require('util');
util.inherits(ChunkStream, Readable);

function ChunkStream(chunks, options) {
 chunks.push(null);
  Readable.call(this, options);
  this._chunks = chunks;
}

ChunkStream.prototype._read = function() {
  this.push(this._chunks.shift());
};

module.exports = ChunkStream;

方案二

'use strict';

/**
 * Module dependencies.
 */

var Readable = require('stream').Readable;
var util = require('util');
util.inherits(ChunkStream, Readable);

function ChunkStream(chunks, options) {
  Readable.call(this, options);
  this._chunks = chunks;
}

ChunkStream.prototype._read = function() {
  if (this._chunks.length === 0) {
    return this.push(null);
  }
  this.push(this._chunks.shift());
};

module.exports = ChunkStream;

不知道哪个合理一点, 如果有需要的话我可以分别向这两个repo提PR,等chunkstream修复了以后再向mm模块提PR。 @fengmk2