Skip to content

Commit cfbdea1

Browse files
committed
feat: adds 'expectSuccessStatus' transform
1 parent 981c8b9 commit cfbdea1

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/index.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,23 @@ test('expect status', async () => {
270270
server.close();
271271
});
272272

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+
273290
describe('serialization options', () => {
274291
test('strip empty strings', () => {
275292
expect(

src/index.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export interface ApiCall<Method extends HttpMethod> extends Promise<Response> {
4747
): ApiCall<Method>;
4848

4949
expectStatus(code: number): ApiCall<Method>;
50+
expectSuccessStatus(): ApiCall<Method>;
5051

5152
onResponse(cb: OnResponse): ApiCall<Method>;
5253
onJsonResponse(cb: OnJsonResponse): ApiCall<Method>;
@@ -147,7 +148,19 @@ class ApiCallImpl<Method extends HttpMethod> implements ApiCall<Method> {
147148
expectStatus(code: number) {
148149
return this.onResponse(res => {
149150
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+
});
151164
}
152165
});
153166
}

0 commit comments

Comments
 (0)