-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
68 lines (52 loc) · 1.67 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
const { Readable } = require('stream')
// eslint-disable-next-line import/no-unresolved
const test = require('ava')
// eslint-disable-next-line import/no-unresolved
const { parse } = require('csv-parse/sync')
const Fastify = require('fastify')
const supertest = require('supertest')
const { fastifyStreamToCsv } = require('./index')
test('Namespace should exist:', async (t) => {
const fastify = Fastify()
t.teardown(() => fastify.close())
fastify.register(fastifyStreamToCsv)
await fastify.ready()
t.true(fastify.hasReplyDecorator('streamToCsv'), 'has streamToCsv reply decorator')
})
test('Should create a CSV file:', async (t) => {
const fastify = Fastify()
t.teardown(() => fastify.close())
fastify.register(fastifyStreamToCsv)
fastify.get('/', async function report (req, reply) {
const readStream = Readable.from(Array.from(Array(1).keys()))
const rowFormatter = num => [`a${num}`, `b${num}`, `c${num}`]
await reply.streamToCsv(readStream, rowFormatter, {
csvOptions: {
headers: ['a', 'b', 'c']
}
})
return reply
})
await fastify.ready()
const response = await supertest(fastify.server)
.get('/')
.buffer()
.parse((res, callback) => {
res.setEncoding('binary')
res.data = ''
res.on('data', (chunk) => {
res.data += chunk
})
res.on('end', () => {
callback(null, Buffer.from(res.data, 'binary'))
})
})
t.is(response.statusCode, 200)
t.is(response.headers['content-type'], 'text/csv')
t.not(response.headers['content-length'], 0)
const csvResponse = parse(response.body)
t.deepEqual(csvResponse, [
['a', 'b', 'c'],
['a0', 'b0', 'c0']
])
})