From db29978fe089d7dd4c90cd92e9846ee1bbb19a76 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Mon, 18 Mar 2019 07:58:42 -0700 Subject: [PATCH] fix: throw error when inserting menu items out-of-range (#17401) * fix: throw error when inserting menu items out-of-range * also check pos < 0 --- lib/browser/api/menu.js | 6 ++++++ spec/api-menu-spec.js | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/lib/browser/api/menu.js b/lib/browser/api/menu.js index c8e25b5e6e47..e8c1a7fdf15d 100644 --- a/lib/browser/api/menu.js +++ b/lib/browser/api/menu.js @@ -110,6 +110,12 @@ Menu.prototype.insert = function (pos, item) { throw new TypeError('Invalid item') } + if (pos < 0) { + throw new RangeError(`Position ${pos} cannot be less than 0`) + } else if (pos > this.getItemCount()) { + throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`) + } + // insert item depending on its type insertItemByType.call(this, item, pos) diff --git a/spec/api-menu-spec.js b/spec/api-menu-spec.js index a1a2a6f946c7..720c45b988c6 100644 --- a/spec/api-menu-spec.js +++ b/spec/api-menu-spec.js @@ -688,6 +688,24 @@ describe('Menu module', () => { }) describe('Menu.insert', () => { + it('should throw when attempting to insert at out-of-range indices', () => { + const menu = Menu.buildFromTemplate([ + { label: '1' }, + { label: '2' }, + { label: '3' } + ]) + + const item = new MenuItem({ label: 'badInsert' }) + + expect(() => { + menu.insert(9999, item) + }).to.throw(/Position 9999 cannot be greater than the total MenuItem count/) + + expect(() => { + menu.insert(-9999, item) + }).to.throw(/Position -9999 cannot be less than 0/) + }) + it('should store item in @items by its index', () => { const menu = Menu.buildFromTemplate([ { label: '1' },