UNPKG

als-send-file

Version:

file serving with advanced options for caching, headers, and error handling, compatible with Express middleware.

69 lines (58 loc) 2.66 kB
const http = require('http'); const { describe, it, beforeEach } = require('node:test'); const assert = require('node:assert'); const generateETag = require('../lib/etag'); describe('ETag Tests', () => { let request, response, stats; beforeEach(() => { stats = { mtimeMs: Date.now(), mtime: new Date(), ino: 12345 }; request = new http.IncomingMessage({}); response = new http.ServerResponse({}); response.setHeader = function (key, value) { this.headers = this.headers || {}; this.headers[key] = value; }; response.end = function () { this.ended = true; }; }); it('should set Last-Modified and ETag headers', () => { generateETag(request, response, stats); assert(response.headers['Last-Modified'] === stats.mtime.toUTCString()) assert.strictEqual(response.headers['ETag'], stats.ino.toString() + stats.mtimeMs.toString()); }); it('should set not modified if If-Modified-Since matches', () => { request.headers['if-modified-since'] = stats.mtime.toString(); const result = generateETag(request, response, stats); assert.strictEqual(result, true); assert.strictEqual(response.statusCode, 304); assert.strictEqual(response.ended, true); }); it('should generate ETag and set not modified if ETag matches', () => { request.headers['if-none-match'] = stats.ino + stats.mtimeMs.toString(); const result = generateETag(request, response, stats); const {statusCode,ended} = response assert.strictEqual(result, true); assert.strictEqual(response.statusCode, 304); assert.strictEqual(response.ended, true); }); it('should not set not modified if If-Modified-Since does not match', () => { request.headers['if-modified-since'] = new Date(stats.mtimeMs - 10000).toUTCString(); const result = generateETag(request, response, stats); assert.strictEqual(result, false); }); it('should not set not modified if ETag does not match', () => { request.headers['if-none-match'] = 'wrong'; const result = generateETag(request, response, stats); assert.strictEqual(result, false); }); it('should not set not modified if If-Modified-Since is invalid', () => { request.headers['if-modified-since'] = 'invalid-date'; const result = generateETag(request, response, stats); assert.strictEqual(result, false); }); it('should not set not modified if both If-None-Match and If-Modified-Since are missing', () => { const result = generateETag(request, response, stats); assert.strictEqual(result, false); }); });