1+ const supertest = require ( 'supertest' )
2+ const Koa = require ( 'koa' )
3+ const jsonAsyncIterator = require ( '..' )
4+
5+ describe ( 'koa-json-async-iterator' , ( ) => {
6+ it ( 'should stream an async iterator' , async ( ) => {
7+ const app = new Koa ( )
8+ app . use ( jsonAsyncIterator ( ) )
9+ app . use ( async ctx => {
10+ const iterator = async function * ( ) {
11+ yield new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
12+ yield Promise . resolve ( { foo : 'bar' } )
13+ yield new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
14+ yield Promise . resolve ( { baz : 'qux' } )
15+ }
16+ ctx . body = iterator ( )
17+ } )
18+
19+ const response = await supertest ( app . callback ( ) ) . get ( '/' )
20+ expect ( response . status ) . toBe ( 200 )
21+ expect ( response . headers [ 'content-type' ] ) . toBe ( 'application/json; charset=utf-8' )
22+ expect ( response . body ) . toEqual ( [
23+ { foo : 'bar' } ,
24+ { baz : 'qux' }
25+ ] )
26+ } )
27+
28+ it ( 'should thrown errors' , async ( ) => {
29+ const app = new Koa ( )
30+ app . use ( jsonAsyncIterator ( ) )
31+ app . use ( async ctx => {
32+ const iterator = async function * ( ) {
33+ yield new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
34+ yield Promise . resolve ( { foo : 'bar' } )
35+ yield new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
36+ yield Promise . resolve ( { baz : 'qux' } )
37+ yield new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
38+ throw new Error ( 'test' )
39+ }
40+ ctx . body = iterator ( )
41+ } )
42+
43+ const response = await supertest ( app . callback ( ) ) . get ( '/' )
44+ expect ( response . status ) . toBe ( 200 )
45+ expect ( response . body ) . toEqual ( [
46+ { foo : 'bar' } ,
47+ { baz : 'qux' } ,
48+ { error : {
49+ message : 'test' ,
50+ } }
51+ ] )
52+ } )
53+ } )
0 commit comments