From b46efae19992fcac01ce17427f77859eb5936271 Mon Sep 17 00:00:00 2001 From: Alex LaFroscia Date: Fri, 22 Apr 2016 19:34:21 -0400 Subject: [PATCH] Correctly build full URL from parts The old way of building a URL was too brittle and didn't cover a lot of the different cases that could take place, in different combinations of the host, namespace, and segment having or not having slashes included. The new approach implemented here handles the various cases correctly, and ensures that we do not remove a trailing slash if one was provided. Closes #70 --- tests/unit/ajax-request-test.js | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tests/unit/ajax-request-test.js b/tests/unit/ajax-request-test.js index 668b04c4..c8f51506 100644 --- a/tests/unit/ajax-request-test.js +++ b/tests/unit/ajax-request-test.js @@ -624,3 +624,72 @@ test('it JSON encodes JSON:API "extension" request data automatically', function } }); }); + +test('it correctly creates the URL to request', function(assert) { + class NamespaceLeadingSlash extends AjaxRequest { + static get slashType() { + return 'leading slash'; + } + get namespace() { + return '/bar'; + } + } + + class NamespaceTrailingSlash extends AjaxRequest { + static get slashType() { + return 'trailing slash'; + } + get namespace() { + return 'bar/'; + } + } + + class NamespaceTwoSlash extends AjaxRequest { + static get slashType() { + return 'leading and trailing slash'; + } + get namespace() { + return '/bar/'; + } + } + + class NamespaceNoSlash extends AjaxRequest { + static get slashType() { + return 'no slashes'; + } + get namespace() { + return 'bar'; + } + } + + const hosts = [ + { hostType: 'trailing slash', host: 'http://foo.com/' }, + { hostType: 'no trailing slash', host: 'http://foo.com' } + ]; + + [NamespaceLeadingSlash, NamespaceTrailingSlash, NamespaceTwoSlash, NamespaceNoSlash].forEach((Klass) => { + let req = new Klass(); + + hosts.forEach((exampleHost) => { + const { hostType, host } = exampleHost; + ['/baz', 'baz'].forEach((segment) => { + assert.equal( + req._buildURL(segment, { host }), + 'http://foo.com/bar/baz', + `Host with ${hostType}, Namespace with ${Klass.slashType}, segment: ${segment}` + ); + }); + ['/baz/', 'baz/'].forEach((segment) => { + assert.equal( + req._buildURL(segment, { host }), + 'http://foo.com/bar/baz/', + `Host with ${hostType}, Namespace with ${Klass.slashType}, segment: ${segment}` + ); + }); + }); + }); + + let req = new AjaxRequest(); + assert.equal(req._buildURL('/baz', { host: 'http://foo.com' }), 'http://foo.com/baz', 'Builds URL correctly without namespace'); + assert.equal(req._buildURL('/baz'), '/baz', 'Builds URL correctly without namespace or host'); +});