File tree Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -270,6 +270,23 @@ test('expect status', async () => {
270
270
server . close ( ) ;
271
271
} ) ;
272
272
273
+ test ( 'expect successful status' , async ( ) => {
274
+ const server = http
275
+ . createServer ( ( _ , res ) => {
276
+ res . writeHead ( 400 , { 'Content-Type' : 'application/json' } ) ;
277
+ res . end ( JSON . stringify ( { error : 'Something went wrong' } ) ) ;
278
+ } )
279
+ . listen ( 0 ) ;
280
+
281
+ const { port } = server . address ( ) as { port : number } ;
282
+
283
+ await expect (
284
+ apiCall ( `http://localhost:${ port } ` , HttpMethod . GET ) . expectSuccessStatus ( ) ,
285
+ ) . rejects . toThrow ( ) ;
286
+
287
+ server . close ( ) ;
288
+ } ) ;
289
+
273
290
describe ( 'serialization options' , ( ) => {
274
291
test ( 'strip empty strings' , ( ) => {
275
292
expect (
Original file line number Diff line number Diff line change @@ -47,6 +47,7 @@ export interface ApiCall<Method extends HttpMethod> extends Promise<Response> {
47
47
) : ApiCall < Method > ;
48
48
49
49
expectStatus ( code : number ) : ApiCall < Method > ;
50
+ expectSuccessStatus ( ) : ApiCall < Method > ;
50
51
51
52
onResponse ( cb : OnResponse ) : ApiCall < Method > ;
52
53
onJsonResponse ( cb : OnJsonResponse ) : ApiCall < Method > ;
@@ -147,7 +148,19 @@ class ApiCallImpl<Method extends HttpMethod> implements ApiCall<Method> {
147
148
expectStatus ( code : number ) {
148
149
return this . onResponse ( res => {
149
150
if ( res . status !== code ) {
150
- throw new Error ( `Expected ${ code } response, got ${ res . status } ` ) ;
151
+ throw Object . assign ( new Error ( `Expected ${ code } response, got ${ res . status } ` ) , {
152
+ response : res ,
153
+ } ) ;
154
+ }
155
+ } ) ;
156
+ }
157
+
158
+ expectSuccessStatus ( ) {
159
+ return this . onResponse ( res => {
160
+ if ( res . status < 200 || res . status >= 300 ) {
161
+ throw Object . assign ( new Error ( `Expected a successful response, got ${ res . status } ` ) , {
162
+ response : res ,
163
+ } ) ;
151
164
}
152
165
} ) ;
153
166
}
You can’t perform that action at this time.
0 commit comments