From 617b0c756c45959f413177c2d32fe5922bb9da20 Mon Sep 17 00:00:00 2001 From: Marc Bachmann Date: Sun, 4 Aug 2024 20:34:30 +0200 Subject: [PATCH] Add assertions to detect wrong config options of the breaking change An error is reported if one accidentally passes the headers directly instead of `{headers: {}}. e.g. Error: Invalid config attribute Header-test provided to onPatch. Config: {"Header-test":"test-header"} --- src/index.js | 29 +++++++++++++++++++++++++---- test/basics.spec.js | 2 +- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/index.js b/src/index.js index 74f956a..d68e686 100644 --- a/src/index.js +++ b/src/index.js @@ -82,15 +82,36 @@ MockAdapter.prototype.resetHistory = resetHistory; var methodsWithConfigsAsSecondArg = ["any", "get", "delete", "head", "options"]; function convertDataAndConfigToConfig (method, data, config) { if (methodsWithConfigsAsSecondArg.includes(method)) { - return data || {}; + return validateconfig(method, data || {}); } else { - return Object.assign({}, config || {}, { data: data }); + return validateconfig(method, Object.assign({}, config || {}, { data: data })); } } +var allowedConfigs = ['headers', 'params', 'data']; +function validateconfig (method, config) { + for (var key in config) { + if (!allowedConfigs.includes(key)) { + throw new Error( + 'Invalid config attribute ' + + key + + ' provided to ' + + toMethodName(method) + + '. Config: ' + + JSON.stringify(config) + ); + } + } + + return config; +} + +function toMethodName (method) { + return "on" + method.charAt(0).toUpperCase() + method.slice(1); +} + VERBS.concat("any").forEach(function (method) { - var methodName = "on" + method.charAt(0).toUpperCase() + method.slice(1); - MockAdapter.prototype[methodName] = function (matcher, data, config) { + MockAdapter.prototype[toMethodName(method)] = function (matcher, data, config) { var _this = this; var matcher = matcher === undefined ? /.*/ : matcher; var delay; diff --git a/test/basics.spec.js b/test/basics.spec.js index 735fbfc..706f422 100644 --- a/test/basics.spec.js +++ b/test/basics.spec.js @@ -311,7 +311,7 @@ describe("MockAdapter basics", function () { it("does not match when request header is wrong", function () { var headers = { "Header-test": "test-header" }; - mock.onPatch("/wrongObjHeader", undefined, headers).reply(200); + mock.onPatch("/wrongObjHeader", undefined, { headers: headers }).reply(200); return instance .patch("/wrongObjHeader", undefined, {