-
Notifications
You must be signed in to change notification settings - Fork 64
/
test-utils.ts
70 lines (58 loc) · 1.82 KB
/
test-utils.ts
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
import fs from 'fs'
import path from 'path'
import { Readable } from 'stream'
import { NodeList, Node } from './src'
export const fixtures = [
'LaLaLand',
'ManOfSteel',
'WonderWoman'
]
export const getFilePath = (filename: string, extension: string): string =>
path.join(
__dirname,
`/test/fixtures/${filename}.${extension}`
)
export const getFixture = (filename: string, extension: string): Promise<string> =>
new Promise((resolve, reject) =>
fs.readFile(getFilePath(filename, extension), 'utf8', (err, contents) => {
if (err) reject(err)
resolve(contents)
})
)
export const getFixtureStream = (filename: string, extension: string): Readable =>
fs.createReadStream(getFilePath(filename, extension))
export const writeFile = (filename: string, contents: string) => {
const filepath = path.join(
__dirname,
`/test/fixtures/${filename}`
)
fs.writeFileSync(filepath, contents)
}
export const createStreamFromString = (contents: string) => {
const stream = new Readable({
read() {}
})
stream.push(contents)
stream.push(null)
return stream
}
export const createStreamFromNodes = (nodes: NodeList) => {
const stream = new Readable({ objectMode: true, read() {} })
nodes.forEach(node => stream.push(node))
stream.push(null)
return stream
}
export const pipeline = (stream: Readable): Promise<NodeList> =>
new Promise((resolve, reject) => {
const buffer: NodeList = []
stream.on('data', (chunk: Node) => buffer.push(chunk))
stream.on('error', reject)
stream.on('finish', () => resolve(buffer))
})
export const streamToString = (stream: Readable): Promise<string> =>
new Promise((resolve, reject) => {
let buffer = ''
stream.on('data', (chunk: string) => buffer += chunk)
stream.on('error', reject)
stream.on('finish', () => resolve(buffer))
})