From 8981861c76dec1689cae660301b528702b209c15 Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Wed, 4 Jan 2017 09:09:25 +1300 Subject: [PATCH] DataFormat unit tests --- admin/client/src/lib/DataFormat.js | 10 ++++- admin/client/src/lib/tests/DataFormat-test.js | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 admin/client/src/lib/tests/DataFormat-test.js diff --git a/admin/client/src/lib/DataFormat.js b/admin/client/src/lib/DataFormat.js index 98168612f..48018a904 100644 --- a/admin/client/src/lib/DataFormat.js +++ b/admin/client/src/lib/DataFormat.js @@ -2,7 +2,11 @@ import i18n from 'i18n'; import qs from 'qs'; /** - * Merge existing querystring with new querystring object + * Merge existing querystring with new querystring object. + * Does not deep merge. + * + * Example: + * `urlQuery({ foo: 1 }, { bar: 2 })` returns `'?foo=1&bar=2'` * * @param {Object} locationQuery - Current browser querystring object (window.location.query) * @param {Object} newQuery - New object to update. Set to null to clear instead of merge. @@ -26,7 +30,9 @@ export function urlQuery(locationQuery, newQuery) { /** * Turn flatterned querystring object into recursive nested objects, * similarly to how PHP handles nested querystring objects. - * E.g. turn `{'query[val]': bob}` into `{query: { val: bob }}` + * + * Example: + * `decodeQuery('query[val]=bob')` returns `{query: { val: bob }}` * * @param {String} query - Querystring string * @return {Object} - Unflattened query object diff --git a/admin/client/src/lib/tests/DataFormat-test.js b/admin/client/src/lib/tests/DataFormat-test.js new file mode 100644 index 000000000..eddb27369 --- /dev/null +++ b/admin/client/src/lib/tests/DataFormat-test.js @@ -0,0 +1,38 @@ +/* global jest, jasmine, describe, beforeEach, it, pit, expect, process */ + + +jest.unmock('isomorphic-fetch'); +jest.unmock('../DataFormat'); +jest.unmock('qs'); +jest.unmock('merge'); + +import { urlQuery, decodeQuery } from '../DataFormat'; + + +describe('DataFormat', () => { + + describe('urlQuery()', () => { + it('should return empty string when no newQuery is given', () => { + expect(urlQuery({}, null)).toBe(''); + }); + it('should add new keys', () => { + expect(urlQuery({ foo: 1 }, { bar: 2 })).toBe('?foo=1&bar=2'); + }); + it('should overwrite existing keys', () => { + expect(urlQuery({ foo: 1 }, { foo: 2 })).toBe('?foo=2'); + }); + it('should not deep merge nested keys', () => { + expect(urlQuery({ foo: { bar: 1 } }, { foo: { baz: 2 } })).toBe('?foo%5Bbaz%5D=2'); + }); + }); + + describe('decodeQuery', () => { + it('should decode flat keys', () => { + expect(decodeQuery('?foo=1')).toEqual({ foo: '1' }); + }); + it('should decode nested keys (PHP style)', () => { + expect(decodeQuery('?foo[bar]=1')).toEqual({ foo: { bar: '1' } }); + }); + }); + +});