Skip to content

Commit

Permalink
Add assertions to detect wrong config options of the breaking change
Browse files Browse the repository at this point in the history
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"}
  • Loading branch information
marcbachmann committed Aug 5, 2024
1 parent d491b04 commit 617b0c7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
29 changes: 25 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion test/basics.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down

0 comments on commit 617b0c7

Please # to comment.