-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
112 lines (95 loc) · 2.7 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const test = require('tape');
const assert = require('assert');
const { PassThrough } = require('stream');
const { ToNDJSON } = require('./');
test('converts JSON array of objects to NDJSON', (t) => {
const pass = new PassThrough({
decodeStrings: false,
defaultEncoding: 'utf8',
encoding: 'utf8',
});
let counter = 0;
const expected = ['{"a":1,"b":2}\n', '{"a":3,"b":4}\n'];
pass.on('data', (data) => {
t.strictEqual(data, expected[counter], 'line matches expected JSON value');
counter++;
});
pass.on('finish', () => {
t.strictEqual(counter, 2, 'generates 2 lines');
t.end();
});
const s = new ToNDJSON();
s.pipe(pass);
s.end('[{"a":1,"b":2},{"a":3,"b":4}]');
});
test('converts JSON array of objects to object stream', (t) => {
const pass = new PassThrough({ objectMode: true });
let counter = 0;
const expected = [
{ a: 1, b: 2 },
{ a: 3, b: 4 },
];
pass.on('data', (data) => {
t.deepEqual(data, expected[counter], 'object matches expected JSON value');
counter++;
});
pass.on('finish', () => {
t.strictEqual(counter, 2, 'generates 2 objects');
t.end();
});
const s = new ToNDJSON({ readableObjectMode: true });
s.pipe(pass);
s.end('[{"a":1,"b":2},{"a":3,"b":4}]');
});
test('converts JSON array of objects to NDJSON in chunks', (t) => {
const pass = new PassThrough({
decodeStrings: false,
defaultEncoding: 'utf8',
encoding: 'utf8',
});
let counter = 0;
const expected = ['{"a":1,"b":2}\n', '{"a":3,"b":4}\n'];
pass.on('finish', () => {
t.strictEqual(counter, 2, 'generates 2 objects');
t.end();
});
const s = new ToNDJSON();
s.pipe(pass);
pass.once('data', (data) => {
t.strictEqual(data, '{"a":1,"b":2}\n', 'line matches expected JSON value');
counter++;
});
s.write('[{"a":1,"b":2},{');
pass.once('data', (data) => {
t.strictEqual(data, '{"a":3,"b":4}\n', 'line matches expected JSON value');
counter++;
});
s.write('"a":3,"b":4}');
s.end();
});
test('handles and bubbles up jsonparser errors', (t) => {
const pass = new PassThrough({
decodeStrings: false,
defaultEncoding: 'utf8',
encoding: 'utf8',
});
let counter = 0;
const expected = ['{"a":1,"b":2}\n', '{"a":3,"b":4}\n'];
const s = new ToNDJSON();
s.on('error', (err) => {
t.strictEqual(counter, 1, 'generates 1 objects');
t.ok(err, 'emits an error');
t.end();
});
s.pipe(pass);
pass.once('data', (data) => {
t.strictEqual(data, '{"a":1,"b":2}\n', 'line matches expected JSON value');
counter++;
});
s.write('[{"a":1,"b":2},{');
pass.once('data', (data) => {
throw new Error('This line should not be emitted');
});
s.write('{"a":3,"b":4}');
s.end();
});