|
import { assign } from 'url_search_params' |
|
|
|
describe('url search params utilities', ()=> { |
|
let search |
|
|
|
beforeEach(()=> search = new URLSearchParams()) |
|
|
|
// `toString()` encodes the querystring which we want at runtime but for |
|
// testing it is more readable to decode when comparing in tests. |
|
function queryString() { return decodeURI(search.toString()) } |
|
|
|
describe('assign', ()=> { |
|
it('encodes a simple value', ()=> { |
|
assign(search, 'foo', 'bar') |
|
expect( queryString() ).toEqual('foo=bar') |
|
}) |
|
|
|
it('encodes an array of values', ()=> { |
|
assign(search, 'ltrs', ['a', 'b', 'c']) |
|
expect( queryString() ).toEqual('ltrs[]=a<rs[]=b<rs[]=c') |
|
}) |
|
|
|
it('encodes an object', ()=> { |
|
assign(search, 'animals', { |
|
cat: 'meow', |
|
dog: 'woof', |
|
cow: 'moo', |
|
}) |
|
expect( queryString() ).toEqual('animals[cat]=meow&animals[dog]=woof&animals[cow]=moo') |
|
}) |
|
|
|
it('encodes an object of arrays', ()=> { |
|
assign(search, 'test', { |
|
words: ['house', 'computer', 'desk'], |
|
numbers: ['one', 'two'], |
|
}) |
|
expect( queryString() ).toEqual('test[words][]=house&test[words][]=computer&test[words][]=desk&test[numbers][]=one&test[numbers][]=two') |
|
}) |
|
|
|
it('encodes arrays with objects', ()=> { |
|
assign(search, 'records', [ |
|
{ |
|
name: 'John Doe', |
|
age: 18, |
|
}, |
|
{ |
|
name: 'Jane Jackson', |
|
age: 21, |
|
}, |
|
]) |
|
expect( queryString() ).toEqual('records[][name]=John+Doe&records[][age]=18&records[][name]=Jane+Jackson&records[][age]=21') |
|
}) |
|
|
|
it('encodes nested objects', ()=> { |
|
assign(search, 'nested', { |
|
a: { b: 'c' }, |
|
d: { e: 'f', g: 'h' }, |
|
}) |
|
expect( queryString() ).toEqual('nested[a][b]=c&nested[d][e]=f&nested[d][g]=h') |
|
}) |
|
|
|
it('encodes deeply nested mix of objects and arrays', ()=> { |
|
// We can nest arrays as long as they are not directly nested |
|
const data = {a:[{b:[{c:{e:{f:[{g:'h', i:'j'}]}}}], k: 'l'}, {m: 'n'}]} |
|
assign(search, 'stress_test', data) |
|
|
|
const expected = 'stress_test[a][][b][][c][e][f][][g]=h&stress_test[a][][b][][c][e][f][][i]=j&stress_test[a][][k]=l&stress_test[a][][m]=n' |
|
expect( queryString() ).toEqual(expected) |
|
}) |
|
}) |
|
}) |