strom/tests/demux.spec.ts

110 lines
2.7 KiB
TypeScript
Raw Normal View History

2019-08-28 21:01:51 +00:00
import test from "ava";
import { expect } from "chai";
import { demux, map } from "../src";
2019-08-29 12:50:11 +00:00
import { Writable } from "stream";
2019-08-28 21:01:51 +00:00
interface Test {
key: string;
val: number;
}
test.cb("should spread per key", t => {
t.plan(5);
const input = [
{ key: "a", val: 1 },
2019-08-29 12:50:11 +00:00
{ key: "b", val: 2 },
{ key: "a", val: 3 },
2019-08-28 21:01:51 +00:00
{ key: "c", val: 4 },
];
const results = [
{ key: "a", val: 2 },
2019-08-29 12:50:11 +00:00
{ key: "b", val: 3 },
{ key: "a", val: 4 },
2019-08-28 21:01:51 +00:00
{ key: "c", val: 5 },
];
2019-08-29 12:50:11 +00:00
const destinationStreamKeys = [];
2019-08-28 21:01:51 +00:00
let i = 0;
2019-08-29 12:50:11 +00:00
const sink = new Writable({
objectMode: true,
write(chunk, enc, cb) {
expect(results).to.deep.include(chunk);
expect(input).to.not.deep.include(chunk);
t.pass();
cb();
},
});
2019-08-28 21:01:51 +00:00
const construct = (destKey: string) => {
2019-08-29 12:50:11 +00:00
destinationStreamKeys.push(destKey);
const dest = map((chunk: Test) => {
return {
...chunk,
val: chunk.val + 1,
};
});
dest.pipe(sink);
2019-08-28 21:01:51 +00:00
return dest;
};
const demuxed = demux(construct, { key: "key" }, { objectMode: true });
demuxed.on("finish", () => {
2019-08-29 12:50:11 +00:00
expect(destinationStreamKeys).to.deep.equal(["a", "b", "c"]);
2019-08-28 21:01:51 +00:00
t.pass();
t.end();
2019-08-28 21:01:51 +00:00
});
input.forEach(event => demuxed.write(event));
demuxed.end();
});
2019-08-28 21:04:31 +00:00
test.cb("should spread per key using keyBy", t => {
t.plan(5);
const input = [
{ key: "a", val: 1 },
2019-08-29 12:50:11 +00:00
{ key: "b", val: 2 },
{ key: "a", val: 3 },
2019-08-28 21:04:31 +00:00
{ key: "c", val: 4 },
];
const results = [
{ key: "a", val: 2 },
2019-08-29 12:50:11 +00:00
{ key: "b", val: 3 },
{ key: "a", val: 4 },
2019-08-28 21:04:31 +00:00
{ key: "c", val: 5 },
];
2019-08-29 12:50:11 +00:00
const destinationStreamKeys = [];
const sink = new Writable({
objectMode: true,
write(chunk, enc, cb) {
expect(results).to.deep.include(chunk);
expect(input).to.not.deep.include(chunk);
t.pass();
cb();
},
});
2019-08-28 21:04:31 +00:00
const construct = (destKey: string) => {
2019-08-29 12:50:11 +00:00
destinationStreamKeys.push(destKey);
const dest = map((chunk: Test) => {
return {
...chunk,
val: chunk.val + 1,
};
});
dest.pipe(sink);
2019-08-28 21:04:31 +00:00
return dest;
};
const demuxed = demux(
construct,
{ keyBy: (chunk: any) => chunk.key },
{ objectMode: true },
);
demuxed.on("finish", () => {
2019-08-29 12:50:11 +00:00
expect(destinationStreamKeys).to.deep.equal(["a", "b", "c"]);
2019-08-28 21:04:31 +00:00
t.pass();
t.end();
2019-08-28 21:04:31 +00:00
});
input.forEach(event => demuxed.write(event));
demuxed.end();
});