104 lines
2.5 KiB
JavaScript
104 lines
2.5 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
|
|
const registerErrorPageMiddleware = require('../src/web/middleware/error-page');
|
|
|
|
function setupMiddleware(request) {
|
|
let middleware = null;
|
|
const pages = {
|
|
renderErrorPage(options) {
|
|
return '<html>formatted ' + options.statusCode + ': ' + options.message + '</html>';
|
|
}
|
|
};
|
|
registerErrorPageMiddleware({
|
|
use(value) {
|
|
middleware = value;
|
|
}
|
|
}, pages);
|
|
|
|
const response = {
|
|
statusCode: 200,
|
|
body: null,
|
|
status(code) {
|
|
this.statusCode = code;
|
|
return this;
|
|
},
|
|
get() {
|
|
return '';
|
|
},
|
|
send(body) {
|
|
this.body = body;
|
|
return this;
|
|
},
|
|
sendStatus(code) {
|
|
this.statusCode = code;
|
|
this.body = 'status ' + code;
|
|
return this;
|
|
}
|
|
};
|
|
|
|
middleware(request, response, function () {});
|
|
return response;
|
|
}
|
|
|
|
test('plain browser error responses use the shared formatted page', () => {
|
|
const response = setupMiddleware({
|
|
originalUrl: '/slides/180/edit',
|
|
currentUser: { id: 1 },
|
|
accepts() { return 'html'; },
|
|
get() { return ''; }
|
|
});
|
|
|
|
response.status(404).send('Slide not found');
|
|
|
|
assert.match(response.body, /^<html>formatted 404: Slide not found<\/html>$/);
|
|
});
|
|
|
|
test('API errors retain their response body', () => {
|
|
const response = setupMiddleware({
|
|
originalUrl: '/api/slides/180',
|
|
accepts() { return 'html'; },
|
|
get() { return ''; }
|
|
});
|
|
|
|
response.status(404).send('Slide not found');
|
|
|
|
assert.equal(response.body, 'Slide not found');
|
|
});
|
|
|
|
test('object error responses retain their JSON payload', () => {
|
|
const response = setupMiddleware({
|
|
originalUrl: '/admin/action',
|
|
accepts() { return 'html'; },
|
|
get() { return ''; }
|
|
});
|
|
const payload = { error: 'Request failed' };
|
|
|
|
response.status(400).send(payload);
|
|
|
|
assert.equal(response.body, payload);
|
|
});
|
|
|
|
test('already-rendered HTML errors are left intact', () => {
|
|
const response = setupMiddleware({
|
|
originalUrl: '/reset-password',
|
|
accepts() { return 'html'; },
|
|
get() { return ''; }
|
|
});
|
|
|
|
response.status(400).send('<html>custom form error</html>');
|
|
|
|
assert.equal(response.body, '<html>custom form error</html>');
|
|
});
|
|
|
|
test('sendStatus errors use the shared formatted page for browser requests', () => {
|
|
const response = setupMiddleware({
|
|
originalUrl: '/missing',
|
|
accepts() { return 'html'; },
|
|
get() { return ''; }
|
|
});
|
|
|
|
response.sendStatus(404);
|
|
|
|
assert.match(response.body, /^<html>formatted 404:/);
|
|
}); |