From 0efc56a2962b5fa4cca2abe45172819360c6a658 Mon Sep 17 00:00:00 2001 From: Manuel Jenny Date: Mon, 28 Sep 2020 12:06:25 +0200 Subject: [PATCH] feat: add support for req.hostname --- lib/mockRequest.js | 18 ++++++++++++++++ test/lib/mockRequest.spec.js | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/lib/mockRequest.js b/lib/mockRequest.js index d454024..eadfa17 100644 --- a/lib/mockRequest.js +++ b/lib/mockRequest.js @@ -500,6 +500,24 @@ function createRequest(options) { this.emit('end'); }; + /** + * Function: hostname + * + * Hostname is the main domain of the host without the subdomains and port. + * + */ + mockRequest.hostname = (function() { + if (!mockRequest.headers.host) { + return ''; + } + + var offset = 2; + var hostname = mockRequest.headers.host.split(':')[0].split('.'); + var start = hostname.length - offset; + var end = hostname.length; + return hostname.slice(start, end).join('.'); + }()); + /** * Function: subdomains * diff --git a/test/lib/mockRequest.spec.js b/test/lib/mockRequest.spec.js index 4abef44..d58c9a4 100644 --- a/test/lib/mockRequest.spec.js +++ b/test/lib/mockRequest.spec.js @@ -881,6 +881,47 @@ describe('mockRequest', function() { }); + describe('.hostname', function() { + + it('should return the host\'s main domain', function() { + var options = { + headers: { + host: 'tobi.ferrets.example.com:5000' + } + }; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal('example.com'); + + options.headers.host = 'tobi.ferrets.example.com'; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal('example.com'); + + options.headers.host = 'example.com'; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal('example.com'); + + options.headers.host = 'example.com:8443'; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal('example.com'); + + options.headers.host = 'localhost:3000'; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal('localhost'); + + }); + + it('should return an empty string', function () { + var options = { + headers: { + key1: 'key1' + } + }; + request = mockRequest.createRequest(options); + expect(request.hostname).to.equal(''); + }); + + }); + describe('.subdomains', function() { it('should returns the host subdomains', function() {