Skip to content

Commit

Permalink
feat(MockSTDIN): add reset() method to allow pushing data post-EOF
Browse files Browse the repository at this point in the history
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
  • Loading branch information
caitp committed Oct 12, 2014
1 parent 8970987 commit 177fcbd
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Expand Up @@ -15,6 +15,7 @@ feels like those are needed. Patches welcome.
- [send()](#mockstdinsend)
- [end()](#mockstdinend)
- [restore()](#mockstdinrestore)
- [reset()](#mockstdinreset)

---

Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions lib/mock/stdin.js
Expand Up @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions test/stdin.spec.js
Expand Up @@ -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();
}
};

0 comments on commit 177fcbd

Please sign in to comment.