-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.test.ts
48 lines (36 loc) · 1.38 KB
/
index.test.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
import { expect, test } from "bun:test";
import { cope } from '.'
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const positiveExecution = () => JSON.parse('{"asd": 123}') as Record<string, number>
const failingExecution = () => JSON.parse('_broken_"asd"__: 123}__') as Record<string, number>
test('basic success', () => {
const [syncParse, syncParseErr] = cope(positiveExecution)
expect(syncParse).toEqual({ asd: 123 })
expect(syncParseErr).toBeUndefined()
})
test('basic fail', () => {
const [syncParse, syncParseErr] = cope(failingExecution)
expect(syncParse).toBeUndefined()
expect(syncParseErr).toBeInstanceOf(SyntaxError)
})
test('basic with default', () => {
const [syncParse = { qwe: 789 }, syncParseErr] = cope(failingExecution)
expect(syncParse).toEqual({ qwe: 789 })
expect(syncParseErr).toBeInstanceOf(SyntaxError)
})
test('async success', async () => {
const [syncParse, syncParseErr] = await cope(async () => {
await sleep(20) // simulate async work
return positiveExecution()
})
expect(syncParse).toEqual({ asd: 123 })
expect(syncParseErr).toBeUndefined()
})
test('async fail', async () => {
const [syncParse, syncParseErr] = await cope(async () => {
await sleep(20) // simulate async work
return failingExecution()
})
expect(syncParse).toBeUndefined()
expect(syncParseErr).toBeInstanceOf(SyntaxError)
})