From 207b03081a03bc5a93fc6d9fb2cc9fe8819a46c2 Mon Sep 17 00:00:00 2001 From: Eyk Rehbein Date: Tue, 12 Mar 2024 10:44:17 +0100 Subject: [PATCH] add test for transformer --- tests/errors/0_errors.test.ts | 78 +++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 22 deletions(-) diff --git a/tests/errors/0_errors.test.ts b/tests/errors/0_errors.test.ts index 52ec8ff..9ada06e 100644 --- a/tests/errors/0_errors.test.ts +++ b/tests/errors/0_errors.test.ts @@ -3,14 +3,14 @@ import { z } from 'zod' import request from 'supertest' import express from 'express' import { Handler } from '../../src/index.js' -import { HTTPError } from '../../src/utils/error.js' +import { HTTPError, HTTPStatus } from '../../src/utils/error.js' const app = express() const resolverErrorHandler = new Handler() .validate('params', { userId: z.string() }) .resolve(async (req, res, context) => { - throw new HTTPError(400, 'This should fail') + throw new HTTPError(HTTPStatus.BAD_REQUEST, 'This should fail in resolver') }) .transform((data) => { return { @@ -22,7 +22,24 @@ const resolverErrorHandler = new Handler() }) .express() -app.get('/user/:userId', resolverErrorHandler) +const transformerErrorHandler = new Handler() + .validate('params', { userId: z.string() }) + .resolve(async (req, res, context) => { + return 'ok' + }) + .transform((data) => { + throw new HTTPError(HTTPStatus.BAD_REQUEST, 'This should fail in transformer') + return { + data: { + name: 'Hello World', + }, + meta: {}, + } + }) + .express() + +app.get('/resolver/:userId', resolverErrorHandler) +app.get('/transformer/:userId', transformerErrorHandler) // ALWAYS APPEND ERROR HANDLER AFTER ROUTES app.use((err: any, req: any, res: any, next: any) => { @@ -31,25 +48,42 @@ app.use((err: any, req: any, res: any, next: any) => { // TESTS -describe('Error Tests', () => { - describe('Resolver Error', () => { - it('should return 400 ', (done) => { - request(app) - .get('/user/1') - .expect(400) - .then((res) => { - expect(res.body).toEqual({ - errors: [ - { - message: 'This should fail', - }, - ], - type: 'Bad Request', - }) - - done() +describe('Error Handling', () => { + it('should return error as expected for Resolver', (done) => { + request(app) + .get('/resolver/1') + .expect(400) + .then((res) => { + expect(res.body).toEqual({ + errors: [ + { + message: 'This should fail in resolver', + }, + ], + type: 'Bad Request', }) - .catch(done) - }) + + done() + }) + .catch(done) + }) + + it('should return error as expected for Transformer', (done) => { + request(app) + .get('/transformer/1') + .expect(400) + .then((res) => { + expect(res.body).toEqual({ + errors: [ + { + message: 'This should fail in transformer', + }, + ], + type: 'Bad Request', + }) + + done() + }) + .catch(done) }) })