I am using mocha/supertest/should.js to test my Rest Service
GET /files/<hash>
returns file as stream.
How can I assert in should.js that file contents are the same?
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();
});
});
In
should.js
you can use.eql
to compare Buffer's instances:You have 3 solutions:
First:
Compare the result strings
Second:
Using a loop to read the buffers byte by byte
Third:
Using a third-party module like buffertools and buffertools.compare(buffer, buffer|string) method.
Surprisingly, no one has suggested Buffer.equals. That seems to be the fastest and simplest approach and has been around since v0.11.
So your code would become
tmpBuf.equals(testBuf)
for comparing large files e.g. images when asserting file uploads a comparison of buffers or strings with
should.eql
takes ages. i recommend asserting the buffer hash with the crypto module:an easier approach is asserting the buffer length like so:
instead of using shouldjs as assertion module you can surely use a different tool
Solution using
file-compare
andnode-temp
: