From dff1fa45bbcd41f8a2aa42d8b61255761b506ba8 Mon Sep 17 00:00:00 2001 From: Molly Lloyd Date: Thu, 5 Oct 2017 11:27:02 -0700 Subject: [PATCH] error if invalid 'before' argument is passed to Map#addLayer (#5401) error if invalid 'before' argument is passed to Map#addLayer --- src/style/style.js | 6 ++++++ test/unit/style/style.test.js | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/style/style.js b/src/style/style.js index 31a26aab11b..c6ec6c1ddda 100644 --- a/src/style/style.js +++ b/src/style/style.js @@ -568,7 +568,13 @@ class Style extends Evented { layer.setEventedParent(this, {layer: {id: id}}); + const index = before ? this._order.indexOf(before) : this._order.length; + if (before && index === -1) { + this.fire('error', { message: new Error(`Layer with id "${before}" does not exist on this map.`)}); + return; + } + this._order.splice(index, 0, id); this._layers[id] = layer; diff --git a/test/unit/style/style.test.js b/test/unit/style/style.test.js index b67c91e00e4..2142dfaf365 100644 --- a/test/unit/style/style.test.js +++ b/test/unit/style/style.test.js @@ -1006,6 +1006,28 @@ test('Style#addLayer', (t) => { }); }); + t.test('fire error if before layer does not exist', (t) => { + const style = new Style(new StubMap()); + style.loadJSON(createStyleJSON({ + layers: [{ + id: 'a', + type: 'background' + }, { + id: 'b', + type: 'background' + }] + })); + const layer = {id: 'c', type: 'background'}; + + style.on('style.load', () => { + style.on('error', (error)=>{ + t.match(error.message, /does not exist on this map/); + t.end(); + }); + style.addLayer(layer, 'z'); + }); + }); + t.test('fires an error on non-existant source layer', (t) => { const style = new Style(new StubMap()); style.loadJSON(util.extend(createStyleJSON(), {