Add tests for undefined query params

Fixes #169
This commit is contained in:
Michael Jackson 2019-07-30 15:51:14 -07:00
parent 699b849914
commit 7582c641fb
2 changed files with 10 additions and 3 deletions

View File

@ -5,6 +5,11 @@ describe('createSearch', () => {
expect(createSearch({ a: 'a', b: '' })).toEqual('?a=a&b'); expect(createSearch({ a: 'a', b: '' })).toEqual('?a=a&b');
}); });
it('omits the trailing = for null/undefined values', () => {
expect(createSearch({ a: 'a', b: null })).toEqual('?a=a&b');
expect(createSearch({ a: 'a', b: undefined })).toEqual('?a=a&b');
});
it('sorts keys', () => { it('sorts keys', () => {
expect(createSearch({ b: 'b', a: 'a', c: 'c' })).toEqual('?a=a&b=b&c=c'); expect(createSearch({ b: 'b', a: 'a', c: 'c' })).toEqual('?a=a&b=b&c=c');
}); });

View File

@ -1,12 +1,14 @@
export default function createSearch(query) { export default function createSearch(query) {
const keys = Object.keys(query).sort(); const keys = Object.keys(query).sort();
const params = keys.reduce( const pairs = keys.reduce(
(memo, key) => (memo, key) =>
memo.concat( memo.concat(
query[key] ? `${key}=${encodeURIComponent(query[key])}` : key query[key] == null || query[key] === ''
? key
: `${key}=${encodeURIComponent(query[key])}`
), ),
[] []
); );
return params.length ? `?${params.join('&')}` : ''; return pairs.length ? `?${pairs.join('&')}` : '';
} }