@@ -613,6 +613,74 @@ describe('node-fetch', () => {
613613 } ) ;
614614 } ) ;
615615
616+ it ( 'should handle network-error in chunked response' , ( ) => {
617+ const url = `${ base } error/premature/chunked` ;
618+ return fetch ( url ) . then ( res => {
619+ expect ( res . status ) . to . equal ( 200 ) ;
620+ expect ( res . ok ) . to . be . true ;
621+
622+ return expect ( new Promise ( ( resolve , reject ) => {
623+ res . body . on ( 'error' , reject ) ;
624+ res . body . on ( 'close' , resolve ) ;
625+ } ) ) . to . eventually . be . rejectedWith ( Error , 'Premature close' )
626+ . and . have . property ( 'code' , 'ERR_STREAM_PREMATURE_CLOSE' ) ;
627+ } ) ;
628+ } ) ;
629+
630+ it ( 'should handle network-error in chunked response async iterator' , ( ) => {
631+ const url = `${ base } error/premature/chunked` ;
632+ return fetch ( url ) . then ( res => {
633+ expect ( res . status ) . to . equal ( 200 ) ;
634+ expect ( res . ok ) . to . be . true ;
635+
636+ const read = async body => {
637+ const chunks = [ ] ;
638+
639+ if ( process . version < 'v14' ) {
640+ // In Node.js 12, some errors don't come out in the async iterator; we have to pick
641+ // them up from the event-emitter and then throw them after the async iterator
642+ let error ;
643+ body . on ( 'error' , err => {
644+ error = err ;
645+ } ) ;
646+
647+ for await ( const chunk of body ) {
648+ chunks . push ( chunk ) ;
649+ }
650+
651+ if ( error ) {
652+ throw error ;
653+ }
654+
655+ return new Promise ( resolve => {
656+ body . on ( 'close' , ( ) => resolve ( chunks ) ) ;
657+ } ) ;
658+ }
659+
660+ for await ( const chunk of body ) {
661+ chunks . push ( chunk ) ;
662+ }
663+
664+ return chunks ;
665+ } ;
666+
667+ return expect ( read ( res . body ) )
668+ . to . eventually . be . rejectedWith ( Error , 'Premature close' )
669+ . and . have . property ( 'code' , 'ERR_STREAM_PREMATURE_CLOSE' ) ;
670+ } ) ;
671+ } ) ;
672+
673+ it ( 'should handle network-error in chunked response in consumeBody' , ( ) => {
674+ const url = `${ base } error/premature/chunked` ;
675+ return fetch ( url ) . then ( res => {
676+ expect ( res . status ) . to . equal ( 200 ) ;
677+ expect ( res . ok ) . to . be . true ;
678+
679+ return expect ( res . text ( ) )
680+ . to . eventually . be . rejectedWith ( Error , 'Premature close' ) ;
681+ } ) ;
682+ } ) ;
683+
616684 it ( 'should handle DNS-error response' , ( ) => {
617685 const url = 'http://domain.invalid' ;
618686 return expect ( fetch ( url ) ) . to . eventually . be . rejected
0 commit comments