@@ -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,45 @@ 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 =
81
+ typeof this . sentBody === "undefined"
82
+ ? toSend
83
+ : this . sentBody + String ( toSend || "" ) ;
84
+ this . end ( body ) ;
85
85
}
86
86
87
87
public write ( writeBody : any , cb ?: ( ) => void ) {
88
- this . sentBody += typeof writeBody === "object" ? JSON . stringify ( writeBody ) : writeBody ;
88
+ this . writeCalled = true ;
89
+
90
+ if ( typeof this . sentBody === "undefined" ) {
91
+ this . sentBody = writeBody ;
92
+ } else {
93
+ this . sentBody += typeof writeBody === "object" ? JSON . stringify ( writeBody ) : writeBody ;
94
+ }
89
95
if ( cb ) {
90
96
setImmediate ( cb ) ;
91
97
}
92
98
return true ;
93
99
}
94
100
95
- public end ( ) {
96
- this . send ( undefined ) ;
101
+ public end ( body ?: unknown ) {
102
+ if ( body ) {
103
+ this . write ( body ) ;
104
+ }
105
+ resolve ( {
106
+ status : this . statusCode ,
107
+ headers : this . headers ,
108
+ body : this . sentBody ,
109
+ } ) ;
110
+
111
+ if ( this . callback ) {
112
+ this . callback ( ) ;
113
+ }
97
114
}
98
115
99
116
public on ( event : string , callback : ( ) => void ) {
0 commit comments