From 899118b2e34c3d28fe9154154ef317d93341991a Mon Sep 17 00:00:00 2001 From: Klaus Hartl Date: Sat, 14 Sep 2019 09:49:06 +0200 Subject: [PATCH] Handle falsy arguments passed to getters In case `null` or `undefinded` is passed to one of the getter methods we shouldn't treat it as if it was an attempt to get all cookies. Fixes #399 --- src/js.cookie.mjs | 8 +++++++- test/tests.js | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/js.cookie.mjs b/src/js.cookie.mjs index 02746ea9..ebf97e2b 100644 --- a/src/js.cookie.mjs +++ b/src/js.cookie.mjs @@ -123,9 +123,15 @@ function init (converter) { api.set = set api.get = function (key) { - return get(key, false /* read as raw */) + if (arguments.length && !key) { + return + } + return get(key /* read as raw */) } api.getJSON = function (key) { + if (arguments.length && !key) { + return + } return get(key, true /* read as json */) } api.remove = function (key, attributes) { diff --git a/test/tests.js b/test/tests.js index bebb97a7..695a1cc3 100644 --- a/test/tests.js +++ b/test/tests.js @@ -106,6 +106,20 @@ QUnit.test('Call to read cookie when there is a window.json variable globally', delete window.json }) +QUnit.test('Passing `undefined` first argument', function (assert) { + assert.expect(2) + Cookies.set('foo', 'bar') + assert.strictEqual(Cookies.get(undefined), undefined, 'should not attempt to retrieve all cookies') + assert.strictEqual(Cookies.getJSON(undefined), undefined, 'should not attempt to retrieve all JSON cookies') +}) + +QUnit.test('Passing `null` first argument', function (assert) { + assert.expect(2) + Cookies.set('foo', 'bar') + assert.strictEqual(Cookies.get(null), undefined, 'should not attempt to retrieve all cookies') + assert.strictEqual(Cookies.getJSON(null), undefined, 'should not attempt to retrieve all JSON cookies') +}) + QUnit.module('write', lifecycle) QUnit.test('String primitive', function (assert) {