diff --git a/lib/utils.js b/lib/utils.js index e869bbbd5b..ce82785ad1 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -242,10 +242,7 @@ var storeData = function (input, data) { // Remove _unchecked from arrays of checkboxes if (Array.isArray(val)) { - var index = val.indexOf('_unchecked') - if (index !== -1) { - val.splice(index, 1) - } + val = val.filter((item) => item !== '_unchecked') } else if (typeof val === 'object') { // Store nested objects that aren't arrays if (typeof data[i] !== 'object') { diff --git a/lib/utils.test.js b/lib/utils.test.js index 3ccb398dcb..54ac041ed1 100644 --- a/lib/utils.test.js +++ b/lib/utils.test.js @@ -142,3 +142,53 @@ describe('getRenderOptions', () => { expect(document).toContain('
')
   })
 })
+
+describe('autoStoreData', () => {
+  const req = {
+    session: {}
+  }
+  const res = { }
+
+  beforeEach(() => {
+    req.body = {}
+    req.query = {}
+    req.session.data = {
+      existingData: 'existing data'
+    }
+    res.locals = {}
+  })
+
+  it('strips all properties where the name is prefixed with an underscore when saving the request query to the session and locals data', () => {
+    req.query = {
+      _omitMe: 'omit me',
+      doIncludeMe: 'include me'
+    }
+    const expectedData = {
+      doIncludeMe: 'include me',
+      existingData: 'existing data'
+    }
+    utils.autoStoreData(req, res, () => {
+      expect(res.locals.data).toEqual(expectedData)
+      expect(req.session.data).toEqual(expectedData)
+    })
+  })
+
+  it('removes all occurrences of the value "_unchecked" in checkboxes when saving the request body to the session and locals data', () => {
+    req.body = {
+      checkBoxes1: ['_unchecked', 'cb1-1', '_unchecked', '_unchecked', 'cb1-2', '_unchecked'],
+      checkBoxes2: ['_unchecked', '_unchecked'],
+      checkBoxes3: ['cb3-1', 'cb3-2'],
+      existingData: 'existing data'
+    }
+    const expectedData = {
+      checkBoxes1: ['cb1-1', 'cb1-2'],
+      checkBoxes2: [],
+      checkBoxes3: ['cb3-1', 'cb3-2'],
+      existingData: 'existing data'
+    }
+    utils.autoStoreData(req, res, () => {
+      expect(res.locals.data).toEqual(expectedData)
+      expect(req.session.data).toEqual(expectedData)
+    })
+  })
+})