@@ -113,12 +113,7 @@ export function ressert(res: Response) {
113
113
bodyAsExecutionResult : {
114
114
data : {
115
115
async toBe ( val : ExecutionResult [ 'data' ] ) {
116
- let body : ExecutionResult ;
117
- try {
118
- body = await res . json ( ) ;
119
- } catch ( err ) {
120
- throw new AuditError ( res , 'Response body is not valid JSON' ) ;
121
- }
116
+ const body = await assertBodyAsExecutionResult ( res ) ;
122
117
if ( body . data !== val ) {
123
118
throw new AuditError (
124
119
res ,
@@ -128,12 +123,7 @@ export function ressert(res: Response) {
128
123
} ,
129
124
} ,
130
125
async toHaveProperty ( key : keyof ExecutionResult ) {
131
- let body : ExecutionResult ;
132
- try {
133
- body = await res . json ( ) ;
134
- } catch ( err ) {
135
- throw new AuditError ( res , 'Response body is not valid JSON' ) ;
136
- }
126
+ const body = await assertBodyAsExecutionResult ( res ) ;
137
127
if ( ! ( key in body ) ) {
138
128
throw new AuditError (
139
129
res ,
@@ -142,12 +132,7 @@ export function ressert(res: Response) {
142
132
}
143
133
} ,
144
134
async notToHaveProperty ( key : keyof ExecutionResult ) {
145
- let body : ExecutionResult ;
146
- try {
147
- body = await res . json ( ) ;
148
- } catch ( err ) {
149
- throw new AuditError ( res , 'Response body is not valid JSON' ) ;
150
- }
135
+ const body = await assertBodyAsExecutionResult ( res ) ;
151
136
if ( key in body ) {
152
137
throw new AuditError (
153
138
res ,
@@ -158,3 +143,26 @@ export function ressert(res: Response) {
158
143
} ,
159
144
} ;
160
145
}
146
+
147
+ /** @private */
148
+ async function assertBodyAsExecutionResult (
149
+ res : Response ,
150
+ ) : Promise < ExecutionResult > {
151
+ let decoded : string ;
152
+ try {
153
+ const decoder = new TextDecoder ( 'utf-8' ) ;
154
+ const buff = await res . arrayBuffer ( ) ;
155
+ decoded = decoder . decode ( buff ) ;
156
+ } catch ( err ) {
157
+ throw new AuditError ( res , 'Response body is not UTF-8 encoded' ) ;
158
+ }
159
+
160
+ let body : ExecutionResult ;
161
+ try {
162
+ body = JSON . parse ( decoded ) ;
163
+ } catch ( err ) {
164
+ throw new AuditError ( res , 'Response body is not valid JSON' ) ;
165
+ }
166
+
167
+ return body ;
168
+ }
0 commit comments