From e62360de4a38e939640d11ade4560ac775e66d04 Mon Sep 17 00:00:00 2001 From: Chance Strickland Date: Mon, 16 Aug 2021 16:57:50 -0700 Subject: [PATCH] Normalize hash and search strings (#813) (#891) --- .../history/__tests__/create-path-test.js | 62 +++++++++++++++++++ packages/history/index.ts | 6 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 packages/history/__tests__/create-path-test.js diff --git a/packages/history/__tests__/create-path-test.js b/packages/history/__tests__/create-path-test.js new file mode 100644 index 000000000..236e8afad --- /dev/null +++ b/packages/history/__tests__/create-path-test.js @@ -0,0 +1,62 @@ +import expect from 'expect'; +import { createPath } from 'history'; + +describe('createPath', () => { + describe('given only a pathname', () => { + it('returns the pathname unchanged', () => { + let path = createPath({ pathname: 'https://google.com' }); + expect(path).toBe('https://google.com'); + }); + }); + + describe('given a pathname and a search param', () => { + it('returns the constructed pathname', () => { + let path = createPath({ + pathname: 'https://google.com', + search: '?something=cool' + }); + expect(path).toBe('https://google.com?something=cool'); + }); + }); + + describe('given a pathname and a search param without ?', () => { + it('returns the constructed pathname', () => { + let path = createPath({ + pathname: 'https://google.com', + search: 'something=cool' + }); + expect(path).toBe('https://google.com?something=cool'); + }); + }); + + describe('given a pathname and a hash param', () => { + it('returns the constructed pathname', () => { + let path = createPath({ + pathname: 'https://google.com', + hash: '#section-1' + }); + expect(path).toBe('https://google.com#section-1'); + }); + }); + + describe('given a pathname and a hash param without #', () => { + it('returns the constructed pathname', () => { + let path = createPath({ + pathname: 'https://google.com', + hash: 'section-1' + }); + expect(path).toBe('https://google.com#section-1'); + }); + }); + + describe('given a full location object', () => { + it('returns the constructed pathname', () => { + let path = createPath({ + pathname: 'https://google.com', + search: 'something=cool', + hash: '#section-1' + }); + expect(path).toBe('https://google.com?something=cool#section-1'); + }); + }); +}); diff --git a/packages/history/index.ts b/packages/history/index.ts index f87142246..c7e2ebbfb 100644 --- a/packages/history/index.ts +++ b/packages/history/index.ts @@ -1042,7 +1042,11 @@ export function createPath({ search = '', hash = '' }: PartialPath) { - return pathname + search + hash; + if (search && search !== '?') + pathname += search.charAt(0) === '?' ? search : '?' + search; + if (hash && hash !== '#') + pathname += hash.charAt(0) === '#' ? hash : '#' + hash; + return pathname; } /**