2014-09-11 77 views
6

我使用摩卡/ supertest/should.js来测试我的REST服务断言具有相同内容

GET /files/<hash>回报文件作为流文件。

如何在should.js中声明文件内容相同?

it('should return file as stream', function (done) { 
    var writeStream = fs.createWriteStream('test/fixtures/tmp.json'); 

    var req = api.get('/files/676dfg1430af3595'); 
    req.on('end', function(){ 
     var tmpBuf = fs.readFileSync('test/fixtures/tmp.json'); 
     var testBuf = fs.readFileSync('test/fixtures/test.json'); 

     // How to assert with should.js file contents are the same (tmpBuf == testBuf) 
     // ... 

     done(); 
    }); 
}); 

回答

1

令人惊讶的是,没有人建议Buffer.equals。这似乎是最快和最简单的方法,并且自v0.11以来一直存在。

所以你的代码会变成tmpBuf.equals(testBuf)

3

你有3个解决方案:

首先

比较结果字符串

tmpBuf.toString() === testBuf.toString(); 

使用循环读取|方法

使用第三方模块等buffertools和buffertools.compare(字符串缓冲区,缓冲液):缓冲器由字节

var index = 0, 
    length = tmpBuf.length, 
    match = true; 

while (index < length) { 
    if (tmpBuf[index] === testBuf[index]) { 
     index++; 
    } else { 
     match = false; 
     break; 
    } 
} 

match; // true -> contents are the same, false -> otherwise 

第三字节。

3

should.js你可以使用.eql比较缓冲的情况下:

> var buf1 = new Buffer('abc'); 
undefined 
> var buf2 = new Buffer('abc'); 
undefined 
> var buf3 = new Buffer('dsfg'); 
undefined 
> buf1.should.be.eql(buf1) 
... 
> buf1.should.be.eql(buf2) 
... 
> buf1.should.be.eql(buf3) 
AssertionError: expected <Buffer 61 62 63> to equal <Buffer 64 73 66 67> 
    ... 
> 
2

使用file-comparenode-temp解决方案:

it('should return test2.json as a stream', function (done) { 
    var writeStream = temp.createWriteStream(); 
    temp.track(); 

    var req = api.get('/files/7386afde8992'); 

    req.on('end', function() { 
     comparator.compare(writeStream.path, TEST2_JSON_FILE, function(result, err) { 
      if (err) { 
       return done(err); 
      } 

      result.should.true; 
      done(); 
     }); 
    }); 

    req.pipe(writeStream); 
}); 
0

用于例如比较大的文件图像断言文件上传缓冲区或字符串与should.eql比较需要时间。我建议用加密模块断言缓冲区散:

const buf1Hash = crypto.createHash('sha256').update(buf1).digest(); 
const buf2Hash = crypto.createHash('sha256').update(buf2).digest(); 
buf1Hash.should.eql(buf2Hash); 

一个更简单的方法是断言,像这样的缓冲区长度:

buf1.length.should.eql(buf2.length) 

,而不是使用shouldjs作为断言模块,你一定能使用不同的工具

相关问题