@@ -3,20 +3,21 @@ import {
33 getResponseFailureDetails ,
44} from './newsletterSignupFailureDetails' ;
55
6+ type MockHeaders = Partial < Record < string , string > > ;
7+
8+ const mockHeaders = ( headers : MockHeaders ) => ( {
9+ get : jest . fn ( ) . mockImplementation ( ( headerName : string ) => {
10+ return headers [ headerName . toLowerCase ( ) ] ?? null ;
11+ } ) ,
12+ } ) ;
13+
614const mockResponse = (
715 text : string ,
8- additionalHeaders : Record < string , string > = { } ,
16+ additionalHeaders : MockHeaders = { } ,
917) : Response =>
1018 ( {
1119 text : jest . fn ( ) . mockResolvedValue ( text ) ,
12- headers : {
13- get : jest
14- . fn ( )
15- . mockImplementation (
16- ( headerName : string ) =>
17- additionalHeaders [ headerName . toLowerCase ( ) ] ?? null ,
18- ) ,
19- } ,
20+ headers : mockHeaders ( additionalHeaders ) ,
2021 } ) as unknown as Response ;
2122
2223describe ( 'newsletterSignupFailureDetails' , ( ) => {
@@ -53,15 +54,19 @@ describe('newsletterSignupFailureDetails', () => {
5354 } ) ;
5455
5556 it ( 'returns the error code header when present' , async ( ) => {
56- const response = mockResponse ( 'ignored body' , {
57- 'content-type' : 'text/plain' ,
58- 'email-signup-error-code' : 'already-subscribed' ,
59- } ) ;
57+ const textMock = jest . fn ( ) . mockResolvedValue ( 'ignored body' ) ;
58+ const response = {
59+ text : textMock ,
60+ headers : mockHeaders ( {
61+ 'content-type' : 'text/plain' ,
62+ 'email-signup-error-code' : 'already-subscribed' ,
63+ } ) ,
64+ } as unknown as Response ;
6065
6166 await expect ( getResponseFailureDetails ( response ) ) . resolves . toEqual ( {
6267 errorCode : 'already-subscribed' ,
6368 } ) ;
64- expect ( response . text ) . not . toHaveBeenCalled ( ) ;
69+ expect ( textMock ) . not . toHaveBeenCalled ( ) ;
6570 } ) ;
6671
6772 it ( 'returns undefined for html error pages based on content type' , async ( ) => {
@@ -78,15 +83,7 @@ describe('newsletterSignupFailureDetails', () => {
7883 it ( 'returns undefined when reading the response body throws' , async ( ) => {
7984 const response = {
8085 text : jest . fn ( ) . mockRejectedValue ( new Error ( 'read failed' ) ) ,
81- headers : {
82- get : jest
83- . fn ( )
84- . mockImplementation ( ( headerName : string ) =>
85- headerName . toLowerCase ( ) === 'content-type'
86- ? 'text/plain'
87- : null ,
88- ) ,
89- } ,
86+ headers : mockHeaders ( { 'content-type' : 'text/plain' } ) ,
9087 } as unknown as Response ;
9188
9289 await expect ( getResponseFailureDetails ( response ) ) . resolves . toEqual (
0 commit comments