@jakechampion/cli-testing-library
Version:
Small but powerful library for testing CLI the way it is used by people.
78 lines (77 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Output = void 0;
class Output {
_stdoutHandlers = [];
_stderrHandlers = [];
_stdout = [];
_stderr = [];
replaceStrings = {};
get stdout() {
return this.processStdLineGet(this._stdout);
}
set stdout(value) {
this.processStdLineSet(value, '_stdout');
this._stdoutHandlers.forEach((fn) => {
fn(value[0], 'stdout');
});
}
get stderr() {
return this.processStdLineGet(this._stderr);
}
set stderr(value) {
this.processStdLineSet(value, '_stderr');
this._stderrHandlers.forEach((fn) => {
fn(value[0], 'stderr');
});
}
processStdLineSet = (value, type) => {
value.forEach((input) => {
input
.toString()
.split('\n')
.forEach((line) => {
this[type].push(line);
});
});
};
processStdLineGet = (buffer) => {
const output = buffer
.map((line) => {
let output = line.toString();
for (const [original, replaced] of Object.entries(this.replaceStrings)) {
const reg = new RegExp(original, 'gm');
output = output.replace(reg, replaced);
output = output.trim();
}
return output;
})
.filter((line) => line !== '');
return output;
};
on = (handler, type) => {
if (type === 'stdout') {
this._stdoutHandlers.push(handler);
return;
}
if (type === 'stderr') {
this._stderrHandlers.push(handler);
return;
}
this._stdoutHandlers.push(handler);
this._stderrHandlers.push(handler);
};
off = (handler, type) => {
if (type === 'stdout') {
this._stdoutHandlers = this._stdoutHandlers.filter((item) => item !== handler);
return;
}
if (type === 'stderr') {
this._stderrHandlers = this._stderrHandlers.filter((item) => item !== handler);
return;
}
this._stdoutHandlers = this._stdoutHandlers.filter((item) => item !== handler);
this._stderrHandlers = this._stderrHandlers.filter((item) => item !== handler);
};
}
exports.Output = Output;