UNPKG

1.69 kBJavaScriptView Raw
1'use strict'
2
3const t = require('tap')
4const test = t.test
5const Fastify = require('..')
6const { kRequest } = require('../lib/symbols.js')
7
8test('default 400 on request error', t => {
9 t.plan(4)
10
11 const fastify = Fastify()
12
13 fastify.post('/', function (req, reply) {
14 reply.send({ hello: 'world' })
15 })
16
17 fastify.inject({
18 method: 'POST',
19 url: '/',
20 simulate: {
21 error: true
22 },
23 body: {
24 text: '12345678901234567890123456789012345678901234567890'
25 }
26 }, (err, res) => {
27 t.error(err)
28 t.strictEqual(res.statusCode, 400)
29 t.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8')
30 t.deepEqual(JSON.parse(res.payload), {
31 error: 'Bad Request',
32 message: 'Simulated',
33 statusCode: 400
34 })
35 })
36})
37
38test('default 400 on request error with custom error handler', t => {
39 t.plan(6)
40
41 const fastify = Fastify()
42
43 fastify.setErrorHandler(function (err, request, reply) {
44 t.type(request, 'object')
45 t.type(request, fastify[kRequest])
46 reply
47 .code(err.statusCode)
48 .type('application/json; charset=utf-8')
49 .send(err)
50 })
51
52 fastify.post('/', function (req, reply) {
53 reply.send({ hello: 'world' })
54 })
55
56 fastify.inject({
57 method: 'POST',
58 url: '/',
59 simulate: {
60 error: true
61 },
62 body: {
63 text: '12345678901234567890123456789012345678901234567890'
64 }
65 }, (err, res) => {
66 t.error(err)
67 t.strictEqual(res.statusCode, 400)
68 t.strictEqual(res.headers['content-type'], 'application/json; charset=utf-8')
69 t.deepEqual(JSON.parse(res.payload), {
70 error: 'Bad Request',
71 message: 'Simulated',
72 statusCode: 400
73 })
74 })
75})