|
| 1 | +const assert = require('node:assert') |
| 2 | +const http = require('node:http') |
| 3 | +const { join } = require('node:path') |
| 4 | +const { describe, it, beforeEach, afterEach } = require('node:test') |
| 5 | + |
| 6 | +const express = require('express') |
| 7 | +const nunjucks = require('nunjucks') |
| 8 | +const request = require('supertest') |
| 9 | + |
| 10 | +const originalError = console.error |
| 11 | +let errorCalls = [] |
| 12 | + |
| 13 | +const renderErrorPage = require('../../lib/express-middleware/render-error-page') |
| 14 | + |
| 15 | +const app = express() |
| 16 | +app.set('view engine', 'html') |
| 17 | +nunjucks.configure([join(__dirname, '.')], { |
| 18 | + express: app, |
| 19 | + noCache: true |
| 20 | +}) |
| 21 | + |
| 22 | +app.use(function (_req, _res, _next) { |
| 23 | + throw Error('Template error') |
| 24 | +}) |
| 25 | + |
| 26 | +app.use(renderErrorPage) |
| 27 | + |
| 28 | +const server = http.createServer(app) |
| 29 | + |
| 30 | +describe('renderErrorPage', () => { |
| 31 | + beforeEach(() => { |
| 32 | + errorCalls = [] |
| 33 | + console.error = (...args) => { |
| 34 | + errorCalls.push(args) |
| 35 | + originalError(...args) // Still logs to console |
| 36 | + } |
| 37 | + }) |
| 38 | + |
| 39 | + afterEach(() => { |
| 40 | + console.error = originalError |
| 41 | + }) |
| 42 | + |
| 43 | + it('sets the 500 status code', async () => { |
| 44 | + const response = await request(server).get('/error') |
| 45 | + assert.strictEqual(response.status, 500) |
| 46 | + }) |
| 47 | + |
| 48 | + it('renders the 500.html template', async () => { |
| 49 | + const response = await request(server).get('/error') |
| 50 | + assert.strictEqual(response.text, 'Server error\n') |
| 51 | + }) |
| 52 | + |
| 53 | + it('calls console.error() with the error', async () => { |
| 54 | + await request(server).get('/error') |
| 55 | + assert.strictEqual(errorCalls.length, 1) |
| 56 | + assert.ok(errorCalls[0][0].startsWith('Error: Template error')) |
| 57 | + }) |
| 58 | +}) |
0 commit comments