断言具有相同内容的文件

我正在使用摩卡/ supertest / should.js来testing我的rest服务

GET /files/<hash>将文件作为stream返回。

如何在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(); }); }); 

你有3个解决scheme:

第一

比较结果string

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

第二

使用循环逐字节读取缓冲区

 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 

第三

使用像buffertools和buffertools.compare(缓冲区,缓冲区|string)方法的第三方模块。

should.js您可以使用.eql来比较Buffer的实例:

 > 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> ... > 

使用file-comparenode-temp解决scheme:

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

用于比较大文件,例如断言file upload时的图像,缓冲区或string与should.eql的比较需要时间。 我推荐使用crypto模块声明缓冲区哈希值:

 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作为断言模块,你当然可以使用不同的工具