Skip to content

Commit

Permalink
add test for transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
eykrehbein committed Mar 12, 2024
1 parent 6e7464a commit 207b030
Showing 1 changed file with 56 additions and 22 deletions.
78 changes: 56 additions & 22 deletions tests/errors/0_errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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) => {
Expand All @@ -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)
})
})

0 comments on commit 207b030

Please sign in to comment.