From 177fcbd7a4a0a9d60e95c03acf023621ef85b1b1 Mon Sep 17 00:00:00 2001 From: Caitlin Potter Date: Sun, 12 Oct 2014 11:01:30 -0400 Subject: [PATCH] feat(MockSTDIN): add reset() method to allow pushing data post-EOF Ordinarily, a Readable stream will throw when attempting to push after an EOF. This routine will reset the `ended` state of a Readable stream, preventing it from throwing post-EOF. This prevents being required to re-create a mock STDIN instance during certain tests where a fresh stdin is required. Closes #2 --- README.md | 21 +++++++++++++++++++++ lib/mock/stdin.js | 6 ++++++ test/stdin.spec.js | 18 ++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/README.md b/README.md index f5437e5..4d61104 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ feels like those are needed. Patches welcome. - [send()](#mockstdinsend) - [end()](#mockstdinend) - [restore()](#mockstdinrestore) + - [reset()](#mockstdinreset) --- @@ -81,6 +82,26 @@ Alias for [MockSTDIN#send(null)](#mockstdinsend). Results in dispatching an `end --- +######MockSTDIN#reset() + +**example** + +```js +var stdin = require('mock-stdin').stdin(); +stdin.end(); +stdin.reset(); +stdin.send("some data"); +``` + +Ordinarily, a Readable stream will throw when attempting to push after an EOF. This routine will +reset the `ended` state of a Readable stream, preventing it from throwing post-EOF. This prevents +being required to re-create a mock STDIN instance during certain tests where a fresh stdin is +required. + +**return value**: The `MockSTDIN` instance, for chaining. + +--- + ##[LICENSE](LICENSE) The MIT License (MIT) diff --git a/lib/mock/stdin.js b/lib/mock/stdin.js index 65cd51a..fed7e17 100644 --- a/lib/mock/stdin.js +++ b/lib/mock/stdin.js @@ -93,6 +93,12 @@ MockSTDIN.prototype.restore = function MockSTDINRestore() { return this; }; +MockSTDIN.prototype.reset = function MockSTDINReset() { + var state = this._readableState; + state.ended = false; + return this; +}; + MockSTDIN.prototype._read = function MockSTDINRead(size) { if (size === void 0) size = 256; var count = 0; diff --git a/test/stdin.spec.js b/test/stdin.spec.js index ff9df2c..0e1c641 100644 --- a/test/stdin.spec.js +++ b/test/stdin.spec.js @@ -200,5 +200,23 @@ module.exports.stdin = { test.ok(called, "'end' event was not received."); test.done(); }); + }, + + + "MockSTDIN#reset()": function (test) { + var received = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on("data", function(data) { + received += data; + }); + process.stdin.end(); + process.stdin.reset(); + + test.doesNotThrow(function() { + process.stdin.send("Please don't throw, little lamb!"); + }, "should not throw when sending data after end when reset() called"); + + test.equal(received, "Please don't throw, little lamb!"); + test.done(); } };