Use rewire to mock fs.read and write a nice little mock fs.read

This commit is contained in:
Francis Gulotta 2013-11-12 15:37:16 -05:00
parent c9495a713c
commit fa1621579c
2 changed files with 26 additions and 4 deletions

View file

@ -44,7 +44,8 @@
"grunt": "*",
"grunt-cli": "*",
"grunt-mocha-test": "*",
"grunt-contrib-jshint": "*"
"grunt-contrib-jshint": "*",
"rewire": "~2.0.0"
},
"engines": {
"node": "0.10.x"
@ -56,4 +57,4 @@
"scripts": {
"test": "grunt --verbose"
}
}
}

View file

@ -1,7 +1,8 @@
// This takes a serial-port factory and mocks the shit out of it in complete isolation
// This takes a serial-port factory and mocks the shit out of it in complete isolation per require of this file
"use strict";
var rewire = require('rewire');
var serialPort = require('../serialport');
var serialPort = rewire('../serialport');
var mockSerialportPoller = function (hardware) {
var Poller = function (path, cb) {
@ -112,4 +113,24 @@ var hardware = new Hardware();
serialPort.hardware = hardware;
serialPort.SerialPortBinding = hardware.mockBinding;
serialPort.__set__('fs', {
read: function (path, buffer, offset, length, position, cb) {
var port = hardware.ports[path];
if (!port) {
return cb(new Error(path + " does not exist - please call hardware.createPort(path) first"));
}
if (port.data.length === 0) {
return cb(null, 0, buffer);
}
if ((offset + length) > buffer.length) {
throw new Error("Length extends beyond buffer");
}
var read = port.data.slice(0, length);
port.data = port.data.slice(length);
read.copy(buffer, offset);
cb(null, read.length, buffer);
}
});
module.exports = serialPort;