@@ -47,10 +47,11 @@ export function runHandler(
47
47
// MockResponse mocks an express.Response.
48
48
// This class lives here so it can reference resolve and reject.
49
49
class MockResponse {
50
- private sentBody = "" ;
50
+ private sentBody : string | undefined ;
51
51
private statusCode = 0 ;
52
52
private headers : { [ name : string ] : string } = { } ;
53
53
private callback : ( ) => void ;
54
+ private writeCalled = false ;
54
55
55
56
constructor ( ) {
56
57
request . on ( "close" , ( ) => this . end ( ) ) ;
@@ -71,29 +72,42 @@ export function runHandler(
71
72
}
72
73
73
74
public send ( sendBody : any ) {
74
- const toSend = typeof sendBody === "object" ? JSON . stringify ( sendBody ) : sendBody ;
75
- const body = this . sentBody ? this . sentBody + ( ( toSend as string ) || "" ) : toSend ;
76
-
77
- resolve ( {
78
- status : this . statusCode ,
79
- headers : this . headers ,
80
- body,
81
- } ) ;
82
- if ( this . callback ) {
83
- this . callback ( ) ;
75
+ if ( this . writeCalled ) {
76
+ throw Error ( "Cannot set headers after they are sent to the client" )
84
77
}
78
+
79
+ const toSend = typeof sendBody === "object" ? JSON . stringify ( sendBody ) : sendBody ;
80
+ const body = typeof this . sentBody === 'undefined' ? toSend : this . sentBody + ( ( toSend as string ) || "" ) ;
81
+ this . end ( body ) ;
85
82
}
86
83
87
84
public write ( writeBody : any , cb ?: ( ) => void ) {
88
- this . sentBody += typeof writeBody === "object" ? JSON . stringify ( writeBody ) : writeBody ;
85
+ this . writeCalled = true ;
86
+
87
+ if ( typeof this . sentBody === 'undefined' ) {
88
+ this . sentBody = writeBody ;
89
+ } else {
90
+ this . sentBody += typeof writeBody === "object" ? JSON . stringify ( writeBody ) : writeBody ;
91
+ }
89
92
if ( cb ) {
90
93
setImmediate ( cb ) ;
91
94
}
92
95
return true ;
93
96
}
94
97
95
- public end ( ) {
96
- this . send ( undefined ) ;
98
+ public end ( body ?: unknown ) {
99
+ if ( body ) {
100
+ this . write ( body ) ;
101
+ }
102
+ resolve ( {
103
+ status : this . statusCode ,
104
+ headers : this . headers ,
105
+ body : this . sentBody ,
106
+ } ) ;
107
+
108
+ if ( this . callback ) {
109
+ this . callback ( ) ;
110
+ }
97
111
}
98
112
99
113
public on ( event : string , callback : ( ) => void ) {
0 commit comments