-
Notifications
You must be signed in to change notification settings - Fork 5
/
sse.test.ts
111 lines (100 loc) · 2.77 KB
/
sse.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
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
import { buildWorkers, createWorker } from './utils'
import { createClient } from 'graphql-sse'
beforeAll(() => {
buildWorkers()
})
describe('SSE', () => {
it('should subscribe and update', async () => {
const worker = createWorker('./sse.worker.ts', {
durableObjects: {
NEWS_ARTICLE_OBJECT: 'NewsArticleObject',
},
globalTimers: true,
})
const sseClient = createClient({
url: 'http://localhost:8787/graphql',
fetchFn: worker.dispatchFetch.bind(worker),
})
const subscriptionPromise = new Promise<void>(async (resolve, reject) => {
const unsub = sseClient.subscribe(
{
query: /* GraphQL */ `
subscription {
upvotes(articleId: "1")
}
`,
},
{
next: (data) => {
if (data.data?.upvotes === 1) {
resolve()
unsub()
}
},
error: (error) => reject(error),
complete: () => {},
},
)
setTimeout(() => {
worker.dispatchFetch('http://localhost:8787/graphql', {
method: 'POST',
body: JSON.stringify({
query: /* GraphQL */ `
mutation {
upvote(articleId: "1")
}
`,
}),
})
}, 100)
})
await expect(subscriptionPromise).resolves.toBeUndefined()
})
it('should handle multiple subscriptions correctly', async () => {
const worker = createWorker('./sse.worker.ts', {
durableObjects: {
NEWS_ARTICLE_OBJECT: 'NewsArticleObject',
},
globalTimers: true,
})
const expectedUpvotes = 5
const clients = Array.from({ length: 2 }, () => {
return new Promise<number>((resolve, reject) => {
const sseClient = createClient({
url: 'http://localhost:8787/graphql',
fetchFn: worker.dispatchFetch.bind(worker),
})
let i = 0
const unsub = sseClient.subscribe<Record<string, 'upvotes'>>(
{
query: /* GraphQL */ `
subscription {
upvotes(articleId: "1")
}
`,
},
{
next: () => {
if (++i === expectedUpvotes) {
resolve(i)
unsub()
}
},
error: reject,
complete: () => {},
},
)
})
})
Array.from({ length: expectedUpvotes - 1 }).forEach(() => {
worker.dispatchFetch('http://localhost:8787/graphql', {
method: 'POST',
body: JSON.stringify({ query: `mutation { upvote(articleId: "1") }` }),
})
})
await expect(Promise.all(clients)).resolves.toEqual([
expectedUpvotes,
expectedUpvotes,
])
})
})