diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index 481e0a0..0000000 --- a/.eslintrc +++ /dev/null @@ -1,22 +0,0 @@ -{ - "rules": { - "brace-style": [2, "1tbs", { "allowSingleLine": false }], - "comma-dangle": [2, "only-multiline"], - "curly": [2, "multi-line"], - "eol-last": 2, - "eqeqeq": 2, - "key-spacing": [2, { "beforeColon": false, "afterColon": true }], - "keyword-spacing": 2, - "new-cap": 0, - "no-extra-semi": 2, - "no-multiple-empty-lines": [2, { "max": 1 }], - "no-param-reassign": [2, { "props": false }], - "no-trailing-spaces": 2, - "no-underscore-dangle": 0, - "no-unused-vars": [2, { "args": "none" }], - "object-curly-spacing": [2, "always"], - "padded-blocks": [2, "never"], - "semi": [2, "always"], - "space-before-blocks": [2, "always"] - } -} diff --git a/README.md b/README.md index 867bf34..84d0a37 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,11 @@ axios-mock-adapter works on Node as well as in a browser, it works with axios v0 Mocking a `GET` request ```js -var axios = require("axios"); -var MockAdapter = require("axios-mock-adapter"); +const axios = require("axios"); +const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance -var mock = new MockAdapter(axios); +const mock = new AxiosMockAdapter(axios); // Mock any GET request to /users // arguments for reply are (status, data, headers) @@ -40,11 +40,11 @@ axios.get("/users").then(function (response) { Mocking a `GET` request with specific parameters ```js -var axios = require("axios"); -var MockAdapter = require("axios-mock-adapter"); +const axios = require("axios"); +const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance -var mock = new MockAdapter(axios); +const mock = new AxiosMockAdapter(axios); // Mock GET request to /users when param `searchText` is 'John' // arguments for reply are (status, data, headers) @@ -65,7 +65,7 @@ To add a delay to responses, specify a delay amount (in milliseconds) when insta ```js // All requests using this instance will have a 2 seconds delay: -var mock = new MockAdapter(axiosInstance, { delayResponse: 2000 }); +const mock = new AxiosMockAdapter(axiosInstance, { delayResponse: 2000 }); ``` You can restore the original adapter (which will remove the mocking behavior) @@ -279,7 +279,7 @@ If you set `onNoMatch` option to `passthrough` all requests would be forwarded o ```js // Mock all requests to /foo with HTTP 200, but forward // any others requests to server -var mock = new MockAdapter(axiosInstance, { onNoMatch: "passthrough" }); +const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" }); mock.onAny("/foo").reply(200); ``` @@ -287,7 +287,7 @@ mock.onAny("/foo").reply(200); Using `onNoMatch` option with `throwException` to throw an exception when a request is made without match any handler. It's helpful to debug your test mocks. ```js -var mock = new MockAdapter(axiosInstance, { onNoMatch: "throwException" }); +const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "throwException" }); mock.onAny("/foo").reply(200); @@ -323,9 +323,9 @@ mock.onGet("/product").reply(function (config) { Composing from multiple sources with Promises: ```js -var normalAxios = axios.create(); -var mockAxios = axios.create(); -var mock = new MockAdapter(mockAxios); +const normalAxios = axios.create(); +const mockAxios = axios.create(); +const mock = new AxiosMockAdapter(mockAxios); mock .onGet("/orders") @@ -351,7 +351,7 @@ This is useful for testing. ```js describe("Feature", () => { it("requests an endpoint", (done) => { - var mock = new AxiosMockAdapter(axios); + const mock = new AxiosMockAdapter(axios); mock.onPost("/endpoint").replyOnce(200); feature diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..e9fa0a1 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,65 @@ +"use strict"; + +module.exports = [ + { + ignores: [ + "dist/" + ] + }, + { + languageOptions: { + ecmaVersion: 2022, + sourceType: "commonjs" + }, + + rules: { + "brace-style": [2, "1tbs", { "allowSingleLine": false }], + quotes: [ + 2, + "double", + { + avoidEscape: true, + allowTemplateLiterals: true + } + ], + "comma-dangle": [2, "only-multiline"], + "curly": [2, "multi-line"], + "eol-last": 2, + "eqeqeq": 2, + "key-spacing": [2, { "beforeColon": false, "afterColon": true }], + "keyword-spacing": 2, + "new-cap": 0, + "no-native-reassign": 2, + "no-extra-semi": 2, + "no-multiple-empty-lines": [2, { "max": 1 }], + // "no-param-reassign": [2, { "props": false }], + "no-trailing-spaces": 2, + "no-underscore-dangle": 0, + "no-unused-vars": [ + 2, + { + vars: "all", + args: "none", + caughtErrors: "all", + argsIgnorePattern: "^_", + caughtErrorsIgnorePattern: "^_" + } + ], + "object-curly-spacing": [2, "always"], + "padded-blocks": [2, "never"], + "semi": [2, "always"], + "space-before-blocks": [2, "always"], + "no-var": 2, + "prefer-const": [ + 2, + { + destructuring: "any", + ignoreReadBeforeAssign: true + } + ], + + "prefer-promise-reject-errors": 2, + "prefer-template": 2 + } + } +]; diff --git a/package-lock.json b/package-lock.json index 5a6b994..d733bc0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,21 +1,21 @@ { "name": "axios-mock-adapter", - "version": "2.0.0", + "version": "2.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "axios-mock-adapter", - "version": "2.0.0", + "version": "2.1.0", "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.3", "is-buffer": "^2.0.5" }, "devDependencies": { - "axios": "^1.7.3", + "axios": "^1.7.4", "chai": "^4.3.6", - "eslint": "^8.57.0", + "eslint": "^9.8.0", "mocha": "^10.7.0", "nyc": "^17.0.0", "typescript": "^5.5.4", @@ -419,16 +419,30 @@ "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, + "node_modules/@eslint/config-array": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.17.1.tgz", + "integrity": "sha512-BlYOpej8AQ8Ev9xVqroV7a02JK3SkBAaN9GfMMH9W6Ch8FlQlkjGw4Ir7+FgYwfirivAf4t+GtzuAxqfukmISA==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.4", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", + "integrity": "sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", + "espree": "^10.0.1", + "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", @@ -436,34 +450,28 @@ "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, "node_modules/@eslint/js": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", - "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "version": "9.8.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.8.0.tgz", + "integrity": "sha512-MfluB7EUfxXtv3i/++oh89uzAr4PDI4nn201hsp+qaXqsjAWzinlZEHEfPgAX4doIlKvPG/i0A9dpKxOLII8yA==", "dev": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.11.14", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", - "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", - "deprecated": "Use @eslint/config-array instead", + "node_modules/@eslint/object-schema": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", + "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", "dev": true, - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.2", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, "engines": { - "node": ">=10.10.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@humanwhocodes/module-importer": { @@ -479,12 +487,18 @@ "url": "https://github.com/sponsors/nzakas" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true + "node_modules/@humanwhocodes/retry": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", + "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", @@ -728,12 +742,6 @@ "undici-types": "~6.13.0" } }, - "node_modules/@ungap/structured-clone": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", - "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", - "dev": true - }, "node_modules/@webassemblyjs/ast": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", @@ -1090,9 +1098,9 @@ "dev": true }, "node_modules/axios": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.3.tgz", - "integrity": "sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", + "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", "dev": true, "dependencies": { "follow-redirects": "^1.15.6", @@ -1513,18 +1521,6 @@ "node": ">=0.3.1" } }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/electron-to-chromium": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.4.tgz", @@ -1596,41 +1592,37 @@ } }, "node_modules/eslint": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", - "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "version": "9.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.8.0.tgz", + "integrity": "sha512-K8qnZ/QJzT2dLKdZJVX6W4XOwBzutMYmt0lqUS+JdXgd+HTYFlonFgkJ8s44d/zMPPCnOOk0kMWCApCPhiOy9A==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.0", - "@humanwhocodes/config-array": "^0.11.14", + "@eslint-community/regexpp": "^4.11.0", + "@eslint/config-array": "^0.17.1", + "@eslint/eslintrc": "^3.1.0", + "@eslint/js": "9.8.0", "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.3.0", "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", - "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", + "eslint-scope": "^8.0.2", + "eslint-visitor-keys": "^4.0.0", + "espree": "^10.1.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", + "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", @@ -1644,23 +1636,23 @@ "eslint": "bin/eslint.js" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://eslint.org/donate" } }, "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.2.tgz", + "integrity": "sha512-6E4xmrTw5wtxnLA5wYL3WDfhZ/1bUBGOXV0zQvVRDOtrR8D0p6W7fs3JweNYhwRYeGvd/1CKX2se0/2s7Q/nJA==", "dev": true, "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -1678,18 +1670,42 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", + "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.1.0.tgz", + "integrity": "sha512-M1M6CpiE6ffoigIOWYO9UDP8TMUw9kqb21tf+08IgDYjCsOvCuDt4jQcZmoYxx+w7zlKw9/N0KXfto+I8/FrXA==", "dev": true, "dependencies": { - "acorn": "^8.9.0", + "acorn": "^8.12.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "eslint-visitor-keys": "^4.0.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", + "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -1795,15 +1811,15 @@ } }, "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "dependencies": { - "flat-cache": "^3.0.4" + "flat-cache": "^4.0.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16.0.0" } }, "node_modules/fill-range": { @@ -1861,17 +1877,16 @@ } }, "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "dependencies": { "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" + "keyv": "^4.5.4" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16" } }, "node_modules/flatted": { @@ -2072,15 +2087,12 @@ } }, "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, "engines": { - "node": ">=8" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -2092,12 +2104,6 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "dev": true }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -3921,18 +3927,6 @@ "node": ">=4" } }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", @@ -4641,16 +4635,27 @@ "integrity": "sha512-G/M/tIiMrTAxEWRfLfQJMmGNX28IxBg4PBz8XqQhqUHLFI6TL2htpIB1iQCj144V5ee/JaKyT9/WZ0MGZWfA7A==", "dev": true }, + "@eslint/config-array": { + "version": "0.17.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.17.1.tgz", + "integrity": "sha512-BlYOpej8AQ8Ev9xVqroV7a02JK3SkBAaN9GfMMH9W6Ch8FlQlkjGw4Ir7+FgYwfirivAf4t+GtzuAxqfukmISA==", + "dev": true, + "requires": { + "@eslint/object-schema": "^2.1.4", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + } + }, "@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", + "integrity": "sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==", "dev": true, "requires": { "ajv": "^6.12.4", "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", + "espree": "^10.0.1", + "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", @@ -4659,21 +4664,16 @@ } }, "@eslint/js": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", - "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "version": "9.8.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.8.0.tgz", + "integrity": "sha512-MfluB7EUfxXtv3i/++oh89uzAr4PDI4nn201hsp+qaXqsjAWzinlZEHEfPgAX4doIlKvPG/i0A9dpKxOLII8yA==", "dev": true }, - "@humanwhocodes/config-array": { - "version": "0.11.14", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", - "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", - "dev": true, - "requires": { - "@humanwhocodes/object-schema": "^2.0.2", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - } + "@eslint/object-schema": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", + "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", + "dev": true }, "@humanwhocodes/module-importer": { "version": "1.0.1", @@ -4681,10 +4681,10 @@ "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", "dev": true }, - "@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", + "@humanwhocodes/retry": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", + "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", "dev": true }, "@istanbuljs/load-nyc-config": { @@ -4886,12 +4886,6 @@ "undici-types": "~6.13.0" } }, - "@ungap/structured-clone": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", - "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", - "dev": true - }, "@webassemblyjs/ast": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", @@ -5185,9 +5179,9 @@ "dev": true }, "axios": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.3.tgz", - "integrity": "sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", + "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", "dev": true, "requires": { "follow-redirects": "^1.15.6", @@ -5491,15 +5485,6 @@ "integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==", "dev": true }, - "doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "requires": { - "esutils": "^2.0.2" - } - }, "electron-to-chromium": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.4.tgz", @@ -5553,41 +5538,37 @@ "dev": true }, "eslint": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", - "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "version": "9.8.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.8.0.tgz", + "integrity": "sha512-K8qnZ/QJzT2dLKdZJVX6W4XOwBzutMYmt0lqUS+JdXgd+HTYFlonFgkJ8s44d/zMPPCnOOk0kMWCApCPhiOy9A==", "dev": true, "requires": { "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.0", - "@humanwhocodes/config-array": "^0.11.14", + "@eslint-community/regexpp": "^4.11.0", + "@eslint/config-array": "^0.17.1", + "@eslint/eslintrc": "^3.1.0", + "@eslint/js": "9.8.0", "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.3.0", "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", - "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", + "eslint-scope": "^8.0.2", + "eslint-visitor-keys": "^4.0.0", + "espree": "^10.1.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", + "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", @@ -5596,12 +5577,20 @@ "optionator": "^0.9.3", "strip-ansi": "^6.0.1", "text-table": "^0.2.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", + "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", + "dev": true + } } }, "eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.2.tgz", + "integrity": "sha512-6E4xmrTw5wtxnLA5wYL3WDfhZ/1bUBGOXV0zQvVRDOtrR8D0p6W7fs3JweNYhwRYeGvd/1CKX2se0/2s7Q/nJA==", "dev": true, "requires": { "esrecurse": "^4.3.0", @@ -5615,14 +5604,22 @@ "dev": true }, "espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.1.0.tgz", + "integrity": "sha512-M1M6CpiE6ffoigIOWYO9UDP8TMUw9kqb21tf+08IgDYjCsOvCuDt4jQcZmoYxx+w7zlKw9/N0KXfto+I8/FrXA==", "dev": true, "requires": { - "acorn": "^8.9.0", + "acorn": "^8.12.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "eslint-visitor-keys": "^4.0.0" + }, + "dependencies": { + "eslint-visitor-keys": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", + "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", + "dev": true + } } }, "esprima": { @@ -5700,12 +5697,12 @@ } }, "file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "requires": { - "flat-cache": "^3.0.4" + "flat-cache": "^4.0.0" } }, "fill-range": { @@ -5745,14 +5742,13 @@ "dev": true }, "flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "requires": { "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" + "keyv": "^4.5.4" } }, "flatted": { @@ -5886,13 +5882,10 @@ "dev": true }, "globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "dev": true, - "requires": { - "type-fest": "^0.20.2" - } + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true }, "graceful-fs": { "version": "4.2.11", @@ -5900,12 +5893,6 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "dev": true }, - "graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true - }, "has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -7223,12 +7210,6 @@ "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", "dev": true }, - "type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true - }, "typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", diff --git a/package.json b/package.json index 45ea669..2f6d5c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "axios-mock-adapter", - "version": "2.0.0", + "version": "2.1.0", "description": "Axios adapter that allows to easily mock requests", "main": "src/index.js", "scripts": { @@ -41,9 +41,9 @@ "axios": ">= 0.17.0" }, "devDependencies": { - "axios": "^1.7.3", + "axios": "^1.7.4", "chai": "^4.3.6", - "eslint": "^8.57.0", + "eslint": "^9.8.0", "mocha": "^10.7.0", "nyc": "^17.0.0", "typescript": "^5.5.4", diff --git a/src/handle_request.js b/src/handle_request.js index 397d156..4b97b19 100644 --- a/src/handle_request.js +++ b/src/handle_request.js @@ -1,63 +1,31 @@ "use strict"; +const utils = require("./utils"); -var utils = require("./utils"); - -function transformRequest(data) { - if ( - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isBlob(data) - ) { - return data; - } - - // Object and Array: returns a deep copy - if (utils.isObjectOrArray(data)) { - return JSON.parse(JSON.stringify(data)); - } - - // for primitives like string, undefined, null, number - return data; -} - -function makeResponse(result, config) { - return { - status: result[0], - data: transformRequest(result[1]), - headers: result[2], - config: config, - request: { - responseURL: config.url, - }, - }; -} - -function passThroughRequest (mockAdapter, resolve, reject, config) { +function passThroughRequest (mockAdapter, config) { // Axios v0.17 mutates the url to include the baseURL for non hostnames // but does not remove the baseURL from the config - var baseURL = config.baseURL; - if (config.baseURL && !/^https?:/.test(config.baseURL)) { + let baseURL = config.baseURL; + if (baseURL && !/^https?:/.test(baseURL)) { baseURL = undefined; } // Axios pre 1.2 - if (typeof mockAdapter.originalAdapter === 'function') { - return mockAdapter.originalAdapter(config).then(resolve, reject); + if (typeof mockAdapter.originalAdapter === "function") { + return mockAdapter.originalAdapter(config); } - mockAdapter.axiosInstanceWithoutInterceptors(Object.assign({}, config, { - baseURL: baseURL, + return mockAdapter.axiosInstanceWithoutInterceptors(Object.assign({}, config, { + baseURL, // Use the original adapter, not the mock adapter adapter: mockAdapter.originalAdapter, // The request transformation runs on the original axios handler already transformRequest: [], transformResponse: [] - })).then(resolve, reject); + })); } -function handleRequest(mockAdapter, resolve, reject, config) { - var url = config.url || ""; +async function handleRequest(mockAdapter, config) { + let url = config.url || ""; // TODO we're not hitting this `if` in any of the tests, investigate if ( config.baseURL && @@ -67,95 +35,46 @@ function handleRequest(mockAdapter, resolve, reject, config) { } delete config.adapter; - mockAdapter.history[config.method].push(config); + mockAdapter.history.push(config); - var handler = utils.findHandler( + const handler = utils.findHandler( mockAdapter.handlers, config.method, url, config.data, config.params, - (config.headers && config.headers.constructor.name === 'AxiosHeaders') + (config.headers && config.headers.constructor.name === "AxiosHeaders") ? Object.assign({}, config.headers.toJSON()) : config.headers, config.baseURL ); if (handler) { - if (handler[6] === true) { + if (handler.replyOnce) { utils.purgeIfReplyOnce(mockAdapter, handler); } - if (handler.length === 2) { + if (handler.passThrough) { // passThrough handler - passThroughRequest(mockAdapter, resolve, reject, config); - } else if (typeof handler[3] !== "function") { - utils.settle( - resolve, - reject, - makeResponse(handler.slice(3), config), + return passThroughRequest(mockAdapter, config); + } else { + return utils.settle( + config, + handler.response, getEffectiveDelay(mockAdapter, handler) ); - } else { - var result = handler[3](config); - // TODO throw a sane exception when return value is incorrect - if (typeof result.then !== "function") { - utils.settle( - resolve, - reject, - makeResponse(result, config), - getEffectiveDelay(mockAdapter, handler) - ); - } else { - result.then( - function (result) { - if (result.config && result.status) { - utils.settle( - resolve, - reject, - makeResponse( - [result.status, result.data, result.headers], - result.config - ), - 0 - ); - } else { - utils.settle( - resolve, - reject, - makeResponse(result, config), - getEffectiveDelay(mockAdapter, handler) - ); - } - }, - function (error) { - if (mockAdapter.delayResponse > 0) { - setTimeout(function () { - reject(error); - }, getEffectiveDelay(mockAdapter, handler)); - } else { - reject(error); - } - } - ); - } } } else { // handler not found switch (mockAdapter.onNoMatch) { case "passthrough": - passThroughRequest(mockAdapter, resolve, reject, config); - break; + return passThroughRequest(mockAdapter, config); case "throwException": throw utils.createCouldNotFindMockError(config); default: - utils.settle( - resolve, - reject, - { - status: 404, - config: config, - }, + return utils.settle( + config, + { status: 404 }, mockAdapter.delayResponse ); } @@ -163,8 +82,7 @@ function handleRequest(mockAdapter, resolve, reject, config) { } function getEffectiveDelay(adapter, handler) { - var delayPerRequest = handler[7]; - return typeof delayPerRequest === 'number' ? delayPerRequest : adapter.delayResponse; + return typeof handler.delay === "number" ? handler.delay : adapter.delayResponse; } module.exports = handleRequest; diff --git a/src/index.js b/src/index.js index cde8c28..b27afb0 100644 --- a/src/index.js +++ b/src/index.js @@ -1,9 +1,8 @@ "use strict"; +const handleRequest = require("./handle_request"); +const utils = require("./utils"); -var handleRequest = require("./handle_request"); -var utils = require("./utils"); - -var VERBS = [ +const VERBS = [ "get", "post", "head", @@ -16,70 +15,68 @@ var VERBS = [ "unlink", ]; -function adapter() { - return function (config) { - var mockAdapter = this; - return new Promise(function (resolve, reject) { - handleRequest(mockAdapter, resolve, reject, config); +function getVerbArray() { + const arr = []; + VERBS.forEach(function (verb) { + Object.defineProperty(arr, verb, { + get () { + return arr.filter(function (h) { + return !h.method || h.method === verb; + }); + }, }); - }.bind(this); -} - -function getVerbObject() { - return VERBS.reduce(function (accumulator, verb) { - accumulator[verb] = []; - return accumulator; - }, {}); -} - -function reset() { - resetHandlers.call(this); - resetHistory.call(this); -} - -function resetHandlers() { - this.handlers = getVerbObject(); -} - -function resetHistory() { - this.history = getVerbObject(); + }); + return arr; } -function MockAdapter(axiosInstance, options) { - reset.call(this); - - if (axiosInstance) { - this.axiosInstance = axiosInstance; - // Clone the axios instance to remove interceptors - // this is used for the passThrough mode with axios > 1.2 - this.axiosInstanceWithoutInterceptors = axiosInstance.create - ? axiosInstance.create() - : undefined; - - this.originalAdapter = axiosInstance.defaults.adapter; - this.delayResponse = - options && options.delayResponse > 0 ? options.delayResponse : null; - this.onNoMatch = (options && options.onNoMatch) || null; - axiosInstance.defaults.adapter = this.adapter.call(this); - } else { - throw new Error("Please provide an instance of axios to mock"); +class AxiosMockAdapter { + constructor (axiosInstance, options = {}) { + this.reset(); + + if (axiosInstance) { + this.axiosInstance = axiosInstance; + // Clone the axios instance to remove interceptors + // this is used for the passThrough mode with axios > 1.2 + this.axiosInstanceWithoutInterceptors = axiosInstance.create + ? axiosInstance.create() + : undefined; + + this.originalAdapter = axiosInstance.defaults.adapter; + this.delayResponse = options.delayResponse > 0 ? options.delayResponse : null; + this.onNoMatch = options.onNoMatch || null; + axiosInstance.defaults.adapter = this.adapter(); + } else { + throw new Error("Please provide an instance of axios to mock"); + } } -} -MockAdapter.prototype.adapter = adapter; + adapter () { + return (config) => handleRequest(this, config); + } -MockAdapter.prototype.restore = function restore() { - if (this.axiosInstance) { + restore () { + if (!this.axiosInstance) return; this.axiosInstance.defaults.adapter = this.originalAdapter; this.axiosInstance = undefined; } -}; -MockAdapter.prototype.reset = reset; -MockAdapter.prototype.resetHandlers = resetHandlers; -MockAdapter.prototype.resetHistory = resetHistory; + reset () { + this.resetHandlers(); + this.resetHistory(); + } + + resetHandlers () { + if (this.handlers) this.handlers.length = 0; + else this.handlers = getVerbArray(); + } + + resetHistory () { + if (this.history) this.history.length = 0; + else this.history = getVerbArray(); + } +} -var methodsWithConfigsAsSecondArg = ["any", "get", "delete", "head", "options"]; +const methodsWithConfigsAsSecondArg = ["any", "get", "delete", "head", "options"]; function convertDataAndConfigToConfig (method, data, config) { if (methodsWithConfigsAsSecondArg.includes(method)) { return validateconfig(method, data || {}); @@ -88,17 +85,17 @@ function convertDataAndConfigToConfig (method, data, config) { } } -var allowedConfigProperties = ['headers', 'params', 'data']; +const allowedConfigProperties = ["headers", "params", "data"]; function validateconfig (method, config) { - for (var key in config) { + for (const key in config) { if (!allowedConfigProperties.includes(key)) { throw new Error( - 'Invalid config property ' + - JSON.stringify(key) + - ' provided to ' + - toMethodName(method) + - '. Config: ' + - JSON.stringify(config) + `Invalid config property ${ + JSON.stringify(key) + } provided to ${ + toMethodName(method) + }. Config: ${ + JSON.stringify(config)}` ); } } @@ -107,113 +104,136 @@ function validateconfig (method, config) { } function toMethodName (method) { - return "on" + method.charAt(0).toUpperCase() + method.slice(1); + return `on${method.charAt(0).toUpperCase()}${method.slice(1)}`; } VERBS.concat("any").forEach(function (method) { - MockAdapter.prototype[toMethodName(method)] = function (matcher, data, config) { - var _this = this; - var matcher = matcher === undefined ? /.*/ : matcher; - var delay; - var paramsAndBody = convertDataAndConfigToConfig(method, data, config); - - function reply(code, response, headers) { - var handler = [matcher, paramsAndBody, paramsAndBody.headers, code, response, headers, false, delay]; - addHandler(method, _this.handlers, handler); - return _this; + AxiosMockAdapter.prototype[toMethodName(method)] = function (matcher, data, config) { + const self = this; + let delay; + matcher = matcher === undefined ? /.*/ : matcher; + + const paramsAndBody = convertDataAndConfigToConfig(method, data, config); + + function reply (code, response, headers) { + const handler = { + url: matcher, + method: method === "any" ? undefined : method, + params: paramsAndBody.params, + data: paramsAndBody.data, + headers: paramsAndBody.headers, + replyOnce: false, + delay, + response: typeof code === "function" ? code : [ + code, + response, + headers + ] + }; + addHandler(method, self.handlers, handler); + return self; } - function withDelayInMs(_delay) { + function withDelayInMs (_delay) { delay = _delay; - var respond = requestApi.reply.bind(requestApi); + const respond = requestApi.reply.bind(requestApi); Object.assign(respond, requestApi); return respond; } - function replyOnce(code, response, headers) { - var handler = [matcher, paramsAndBody, paramsAndBody.headers, code, response, headers, true, delay]; - addHandler(method, _this.handlers, handler); - return _this; + function replyOnce (code, response, headers) { + const handler = { + url: matcher, + method: method === "any" ? undefined : method, + params: paramsAndBody.params, + data: paramsAndBody.data, + headers: paramsAndBody.headers, + replyOnce: true, + delay: delay, + response: typeof code === "function" ? code : [ + code, + response, + headers + ] + }; + addHandler(method, self.handlers, handler); + return self; } - var requestApi = { - reply: reply, - - replyOnce: replyOnce, - - withDelayInMs: withDelayInMs, - - passThrough: function passThrough() { - var handler = [matcher, paramsAndBody]; - addHandler(method, _this.handlers, handler); - return _this; + const requestApi = { + reply, + replyOnce, + withDelayInMs, + passThrough () { + const handler = { + passThrough: true, + method: method === "any" ? undefined : method, + url: matcher, + params: paramsAndBody.params, + data: paramsAndBody.data, + headers: paramsAndBody.headers + }; + addHandler(method, self.handlers, handler); + return self; }, - - abortRequest: function () { - return reply(function (config) { - var error = utils.createAxiosError( + abortRequest () { + return reply(async function (config) { + throw utils.createAxiosError( "Request aborted", config, undefined, "ECONNABORTED" ); - return Promise.reject(error); }); }, - - abortRequestOnce: function () { - return replyOnce(function (config) { - var error = utils.createAxiosError( + abortRequestOnce () { + return replyOnce(async function (config) { + throw utils.createAxiosError( "Request aborted", config, undefined, "ECONNABORTED" ); - return Promise.reject(error); }); }, - networkError: function () { - return reply(function (config) { - var error = utils.createAxiosError("Network Error", config); - return Promise.reject(error); + networkError () { + return reply(async function (config) { + throw utils.createAxiosError("Network Error", config); }); }, - networkErrorOnce: function () { - return replyOnce(function (config) { - var error = utils.createAxiosError("Network Error", config); - return Promise.reject(error); + networkErrorOnce () { + return replyOnce(async function (config) { + throw utils.createAxiosError("Network Error", config); }); }, - timeout: function () { - return reply(function (config) { - var error = utils.createAxiosError( + timeout () { + return reply(async function (config) { + throw utils.createAxiosError( config.timeoutErrorMessage || - "timeout of " + config.timeout + "ms exceeded", + `timeout of ${config.timeout }ms exceeded`, config, undefined, config.transitional && config.transitional.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED" ); - return Promise.reject(error); }); }, - timeoutOnce: function () { - return replyOnce(function (config) { - var error = utils.createAxiosError( + timeoutOnce () { + return replyOnce(async function (config) { + throw utils.createAxiosError( config.timeoutErrorMessage || - "timeout of " + config.timeout + "ms exceeded", + `timeout of ${config.timeout }ms exceeded`, config, undefined, config.transitional && config.transitional.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED" ); - return Promise.reject(error); }); }, }; @@ -222,43 +242,44 @@ VERBS.concat("any").forEach(function (method) { }; }); -function findInHandlers(method, handlers, handler) { - var index = -1; - for (var i = 0; i < handlers[method].length; i += 1) { - var item = handlers[method][i]; - var isReplyOnce = item[6] === true; - var comparePaths = - item[0] instanceof RegExp && handler[0] instanceof RegExp - ? String(item[0]) === String(handler[0]) - : item[0] === handler[0]; - var isSame = +function findInHandlers (handlers, handler) { + let index = -1; + for (let i = 0; i < handlers.length; i += 1) { + const item = handlers[i]; + const comparePaths = + item.url instanceof RegExp && handler.url instanceof RegExp + ? String(item.url) === String(handler.url) + : item.url === handler.url; + + const isSame = + (!item.method || item.method === handler.method) && comparePaths && - utils.isEqual(item[1], handler[1]) && - utils.isEqual(item[2], handler[2]); - if (isSame && !isReplyOnce) { + utils.isEqual(item.params, handler.params) && + utils.isEqual(item.data, handler.data) && + utils.isEqual(item.headers, handler.headers); + + if (isSame && !item.replyOnce) { index = i; } } return index; } -function addHandler(method, handlers, handler) { +function addHandler (method, handlers, handler) { if (method === "any") { - VERBS.forEach(function (verb) { - handlers[verb].push(handler); - }); + handlers.push(handler); } else { - var indexOfExistingHandler = findInHandlers(method, handlers, handler); - // handler[6] !== true indicates that a handler only runs once. + const indexOfExistingHandler = findInHandlers(handlers, handler); + // handler.replyOnce indicates that a handler only runs once. // It's supported to register muliple ones like that without // overwriting the previous one. - if (indexOfExistingHandler > -1 && handler[6] !== true) { - handlers[method].splice(indexOfExistingHandler, 1, handler); + if (indexOfExistingHandler > -1 && !handler.replyOnce) { + handlers.splice(indexOfExistingHandler, 1, handler); } else { - handlers[method].push(handler); + handlers.push(handler); } } } -module.exports = MockAdapter; -module.exports.default = MockAdapter; +module.exports = AxiosMockAdapter; +module.exports.default = AxiosMockAdapter; diff --git a/src/is_blob.js b/src/is_blob.js index b173540..759c300 100644 --- a/src/is_blob.js +++ b/src/is_blob.js @@ -18,11 +18,11 @@ */ function isBlob(value) { - if (typeof Blob === 'undefined') { + if (typeof Blob === "undefined") { return false; } - return value instanceof Blob || Object.prototype.toString.call(value) === '[object Blob]'; + return value instanceof Blob || Object.prototype.toString.call(value) === "[object Blob]"; } module.exports = isBlob; diff --git a/src/utils.js b/src/utils.js index ba06240..51f5285 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,15 +1,14 @@ "use strict"; - -var axios = require("axios"); -var isEqual = require("fast-deep-equal"); -var isBuffer = require("is-buffer"); -var isBlob = require("./is_blob"); -var toString = Object.prototype.toString; +const axios = require("axios"); +const isEqual = require("fast-deep-equal"); +const isBuffer = require("is-buffer"); +const isBlob = require("./is_blob"); +const toString = Object.prototype.toString; function find(array, predicate) { - var length = array.length; - for (var i = 0; i < length; i++) { - var value = array[i]; + const length = array.length; + for (let i = 0; i < length; i++) { + const value = array[i]; if (predicate(value)) return value; } } @@ -32,7 +31,7 @@ function isArrayBuffer(val) { function combineUrls(baseURL, url) { if (baseURL) { - return baseURL.replace(/\/+$/, "") + "/" + url.replace(/^\/+/, ""); + return `${baseURL.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`; } return url; @@ -48,30 +47,30 @@ function findHandler( baseURL ) { return find(handlers[method.toLowerCase()], function (handler) { - var matchesUrl = false; - if (typeof handler[0] === "string") { - matchesUrl = isUrlMatching(url, handler[0]) || - isUrlMatching(combineUrls(baseURL, url), handler[0]); - } else if (handler[0] instanceof RegExp) { - matchesUrl = handler[0].test(url) || - handler[0].test(combineUrls(baseURL, url)); + let matchesUrl = false; + if (typeof handler.url === "string") { + matchesUrl = isUrlMatching(url, handler.url) || + isUrlMatching(combineUrls(baseURL, url), handler.url); + } else if (handler.url instanceof RegExp) { + matchesUrl = handler.url.test(url) || + handler.url.test(combineUrls(baseURL, url)); } return matchesUrl && - isBodyOrParametersMatching(body, parameters, handler[1]) && - isObjectMatching(headers, handler[2]); + isBodyOrParametersMatching(body, parameters, handler) && + isObjectMatching(headers, handler.headers); }); } function isUrlMatching(url, required) { - var noSlashUrl = url[0] === "/" ? url.substr(1) : url; - var noSlashRequired = required[0] === "/" ? required.substr(1) : required; + const noSlashUrl = url[0] === "/" ? url.substr(1) : url; + const noSlashRequired = required[0] === "/" ? required.substr(1) : required; return noSlashUrl === noSlashRequired; } function isBodyOrParametersMatching(body, parameters, required) { - return isObjectMatching(parameters, required && required.params) && - isBodyMatching(body, required && required.data); + return isObjectMatching(parameters, required.params) && + isBodyMatching(body, required.data); } function isObjectMatching(actual, expected) { @@ -86,41 +85,72 @@ function isBodyMatching(body, requiredBody) { if (requiredBody === undefined) { return true; } - var parsedBody; + let parsedBody; try { parsedBody = JSON.parse(body); - } catch (e) {} + } catch (_e) {} return isObjectMatching(parsedBody ? parsedBody : body, requiredBody); } function purgeIfReplyOnce(mock, handler) { - Object.keys(mock.handlers).forEach(function (key) { - var index = mock.handlers[key].indexOf(handler); - if (index > -1) { - mock.handlers[key].splice(index, 1); - } - }); + const index = mock.handlers.indexOf(handler); + if (index > -1) { + mock.handlers.splice(index, 1); + } } -function settle(resolve, reject, response, delay) { - if (delay > 0) { - setTimeout(settle, delay, resolve, reject, response); - return; +function transformRequest(data) { + if ( + isArrayBuffer(data) || + isBuffer(data) || + isStream(data) || + isBlob(data) + ) { + return data; + } + + // Object and Array: returns a deep copy + if (isObjectOrArray(data)) { + return JSON.parse(JSON.stringify(data)); } + // for primitives like string, undefined, null, number + return data; +} + +async function makeResponse(result, config) { + if (typeof result === "function") result = await result(config); + + const status = result.status || result[0]; + const data = transformRequest(result.data || result[1]); + const headers = result.headers || result[2]; + if (result.config) config = result.config; + + return { + status, + data, + headers, + config, + request: { responseURL: config.url } + }; +} + +async function settle(config, response, delay) { + if (delay > 0) await new Promise(resolve => setTimeout(resolve, delay)); + + const result = await makeResponse(response, config); + if ( - !response.config.validateStatus || - response.config.validateStatus(response.status) + !result.config.validateStatus || + result.config.validateStatus(result.status) ) { - resolve(response); + return result; } else { - reject( - createAxiosError( - "Request failed with status code " + response.status, - response.config, - response - ) + throw createAxiosError( + `Request failed with status code ${result.status}`, + result.config, + result ); } } @@ -132,7 +162,7 @@ function createAxiosError(message, config, response, code) { } // handling for axios v0.26.1 and below - var error = new Error(message); + const error = new Error(message); error.isAxiosError = true; error.config = config; if (response !== undefined) { @@ -164,15 +194,15 @@ function createAxiosError(message, config, response, code) { } function createCouldNotFindMockError(config) { - var message = - "Could not find mock for: \n" + + const message = + `Could not find mock for: \n${ JSON.stringify({ method: config.method, url: config.url, params: config.params, headers: config.headers - }, null, 2); - var error = new Error(message); + }, null, 2)}`; + const error = new Error(message); error.isCouldNotFindMockError = true; error.url = config.url; error.method = config.method; @@ -180,18 +210,15 @@ function createCouldNotFindMockError(config) { } module.exports = { - find: find, - findHandler: findHandler, - purgeIfReplyOnce: purgeIfReplyOnce, - settle: settle, - isStream: isStream, - isArrayBuffer: isArrayBuffer, - isFunction: isFunction, - isObjectOrArray: isObjectOrArray, - isBuffer: isBuffer, - isBlob: isBlob, - isBodyOrParametersMatching: isBodyOrParametersMatching, - isEqual: isEqual, - createAxiosError: createAxiosError, - createCouldNotFindMockError: createCouldNotFindMockError, + find, + findHandler, + purgeIfReplyOnce, + settle, + isObjectOrArray, + isBuffer, + isBlob, + isBodyOrParametersMatching, + isEqual, + createAxiosError, + createCouldNotFindMockError, }; diff --git a/test/abort_request.spec.js b/test/abort_request.spec.js index 219e05f..c554052 100644 --- a/test/abort_request.spec.js +++ b/test/abort_request.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("requestAborted spec", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); diff --git a/test/asymmetric.spec.js b/test/asymmetric.spec.js index 3e8e996..45f30c6 100644 --- a/test/asymmetric.spec.js +++ b/test/asymmetric.spec.js @@ -1,11 +1,10 @@ -var axios = require("axios"); -var expect = require("chai").expect; - -var MockAdapter = require("../src"); +const axios = require("axios"); +const expect = require("chai").expect; +const MockAdapter = require("../src"); describe("MockAdapter asymmetric matchers", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); diff --git a/test/basics.spec.js b/test/basics.spec.js index 8786800..37e59a5 100644 --- a/test/basics.spec.js +++ b/test/basics.spec.js @@ -1,12 +1,12 @@ -var axios = require("axios"); -var fs = require("fs"); -var expect = require("chai").expect; +const axios = require("axios"); +const fs = require("fs"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter basics", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -18,8 +18,8 @@ describe("MockAdapter basics", function () { }); it("correctly throws an error when attempting to instantiate an undefined axios instance", function () { - var emptyInstance = undefined; - var constructorFunc = function () { + const emptyInstance = undefined; + const constructorFunc = function () { new MockAdapter(emptyInstance); }; expect(constructorFunc).to.throw( @@ -189,7 +189,7 @@ describe("MockAdapter basics", function () { .reply(200); return instance - .post("/withParams", { some: 'body' }, { params: { foo: "bar", bar: "foo" } }) + .post("/withParams", { some: "body" }, { params: { foo: "bar", bar: "foo" } }) .then(function (response) { expect(response.status).to.equal(200); }); @@ -201,7 +201,7 @@ describe("MockAdapter basics", function () { .reply(200); return instance - .put("/withParams", { some: 'body' }, { params: { bar: "foo", foo: "bar" } }) + .put("/withParams", { some: "body" }, { params: { bar: "foo", foo: "bar" } }) .then(function (response) { expect(response.status).to.equal(200); }); @@ -261,7 +261,7 @@ describe("MockAdapter basics", function () { }); it("does not match when body is wrong", function () { - var matcher = { somecontent: { is: "passed" } }; + const matcher = { somecontent: { is: "passed" } }; mock.onPatch("/wrongObjBody", matcher).reply(200); return instance @@ -288,7 +288,7 @@ describe("MockAdapter basics", function () { }); it("can pass headers to match to a handler", function () { - var headers = { + const headers = { Accept: "application/json, text/plain, */*", "Content-Type": "application/x-www-form-urlencoded", "Header-test": "test-header", @@ -302,7 +302,7 @@ describe("MockAdapter basics", function () { expect(response.status).to.equal(200); return instance - .post("/withHeaders", undefined, { headers: { Accept: 'no-match' } }) + .post("/withHeaders", undefined, { headers: { Accept: "no-match" } }) .catch(function (err) { expect(err.response.status).to.equal(404); }); @@ -310,7 +310,7 @@ describe("MockAdapter basics", function () { }); it("does not match when request header is wrong", function () { - var headers = { "Header-test": "test-header" }; + const headers = { "Header-test": "test-header" }; mock.onPatch("/wrongObjHeader", undefined, { headers: headers }).reply(200); return instance @@ -465,10 +465,10 @@ describe("MockAdapter basics", function () { }); it("restores the previous adapter (if any)", function () { - var adapter = function () {}; - var newInstance = axios.create(); + const adapter = function () {}; + const newInstance = axios.create(); newInstance.defaults.adapter = adapter; - var newMock = new MockAdapter(newInstance); + const newMock = new MockAdapter(newInstance); newMock.restore(); expect(newInstance.defaults.adapter).to.equal(adapter); @@ -476,7 +476,7 @@ describe("MockAdapter basics", function () { it("performs a noop when restore is called more than once", function () { mock.restore(); - var newAdapter = function () {}; + const newAdapter = function () {}; instance.defaults.adapter = newAdapter; mock.restore(); expect(instance.defaults.adapter).to.equal(newAdapter); @@ -554,37 +554,37 @@ describe("MockAdapter basics", function () { mock = new MockAdapter(instance, { delayResponse: 1 }); mock.onGet("/foo").reply(function (config) { - return Promise.reject("error"); + return Promise.reject(new Error("error")); }); - return instance.get("/foo").catch(function (message) { - expect(message).to.equal("error"); + return instance.get("/foo").catch(function (err) { + expect(err.message).to.equal("error"); }); }); it("allows delay in millsecond per request (legacy non-chaining)", function () { mock = new MockAdapter(instance); - var start = performance.now(); - var firstDelay = 100; - var secondDelay = 500; - var success = 200; + const start = performance.now(); + const firstDelay = 100; + const secondDelay = 500; + const success = 200; - var fooOnDelayResponds = mock.onGet("/foo").withDelayInMs(firstDelay); + const fooOnDelayResponds = mock.onGet("/foo").withDelayInMs(firstDelay); fooOnDelayResponds(success); - var barOnDelayResponds = mock.onGet("/bar").withDelayInMs(secondDelay); + const barOnDelayResponds = mock.onGet("/bar").withDelayInMs(secondDelay); barOnDelayResponds(success); return Promise.all([ instance.get("/foo").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(firstDelay - 1); }), instance.get("/bar").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(secondDelay - 1); @@ -594,10 +594,10 @@ describe("MockAdapter basics", function () { it("allows delay in millsecond per request", function () { mock = new MockAdapter(instance); - var start = performance.now(); - var firstDelay = 100; - var secondDelay = 500; - var success = 200; + const start = performance.now(); + const firstDelay = 100; + const secondDelay = 500; + const success = 200; mock.onGet("/foo") .withDelayInMs(firstDelay) @@ -609,15 +609,15 @@ describe("MockAdapter basics", function () { return Promise.all([ instance.get("/foo").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(firstDelay - 1); }), instance.get("/bar").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(secondDelay - 1); @@ -626,20 +626,20 @@ describe("MockAdapter basics", function () { }); it("overrides global delay if request per delay is provided and respects global delay if otherwise", function () { - var start = performance.now(); - var requestDelay = 100; - var globalDelay = 500; - var success = 200; + const start = performance.now(); + const requestDelay = 100; + const globalDelay = 500; + const success = 200; mock = new MockAdapter(instance, { delayResponse: globalDelay }); - var fooOnDelayResponds = mock.onGet("/foo").withDelayInMs(requestDelay); + const fooOnDelayResponds = mock.onGet("/foo").withDelayInMs(requestDelay); fooOnDelayResponds(success); mock.onGet("/bar").reply(success); return Promise.all([ instance.get("/foo").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(requestDelay - 1); @@ -647,8 +647,8 @@ describe("MockAdapter basics", function () { expect(totalTime).lessThan(globalDelay); }), instance.get("/bar").then(function (response) { - var end = performance.now(); - var totalTime = end - start; + const end = performance.now(); + const totalTime = end - start; expect(response.status).to.equal(success); expect(totalTime).greaterThanOrEqual(globalDelay - 1); @@ -669,7 +669,7 @@ describe("MockAdapter basics", function () { expect(response.data).to.equal("bar"); }), instance - .get("/xyz" + Math.round(100000 * Math.random())) + .get(`/xyz${Math.round(100000 * Math.random())}`) .then(function (response) { expect(response.status).to.equal(200); expect(response.data).to.equal("bar"); @@ -695,7 +695,7 @@ describe("MockAdapter basics", function () { }); it("returns a deep copy of the mock data in the response when the data is an object", function () { - var data = { + const data = { foo: { bar: 123, }, @@ -714,7 +714,7 @@ describe("MockAdapter basics", function () { }); it("returns a deep copy of the mock data in the response when the data is an array", function () { - var data = [ + const data = [ { bar: 123, }, @@ -812,7 +812,7 @@ describe("MockAdapter basics", function () { }); it("allows overwriting only on reply if replyOnce was used first", function () { - var counter = 0; + let counter = 0; mock.onGet("/").replyOnce(500); mock.onGet("/").reply(200); mock.onGet("/").reply(401); @@ -834,7 +834,7 @@ describe("MockAdapter basics", function () { }); it("should not allow overwriting only on reply if replyOnce wasn't used first", function () { - var counter = 0; + let counter = 0; mock.onGet("/").reply(200); mock.onGet("/").reply(401); mock.onGet("/").replyOnce(500); @@ -875,7 +875,7 @@ describe("MockAdapter basics", function () { mock.onGet("/", {}, { "Accept-Charset": "utf-8" }).reply(200); expect(mock.handlers["get"].length).to.equal(1); - expect(mock.handlers["get"][0][3]).to.equal(200); + expect(mock.handlers["get"][0].response[0]).to.equal(200); }); it("supports a retry", function () { @@ -903,8 +903,8 @@ describe("MockAdapter basics", function () { .get("http://www.foo.com/bar", { responseType: "stream" }) .then(function (response) { expect(response.status).to.equal(200); - var stream = response.data; - var string = ""; + const stream = response.data; + let string = ""; stream.on("data", function (chunk) { string += chunk.toString("utf8"); }); @@ -926,7 +926,7 @@ describe("MockAdapter basics", function () { .get("http://www.foo.com/bar", { responseType: "stream" }) .then(function (response) { expect(response.status).to.equal(200); - var string = response.data.toString("utf8"); + const string = response.data.toString("utf8"); expect(string).to.equal("fooBar"); }); }); @@ -940,8 +940,8 @@ describe("MockAdapter basics", function () { }); it("allows sending an Uint8Array as response", function () { - var buffer = new ArrayBuffer(1); - var view = new Uint8Array(buffer); + const buffer = new ArrayBuffer(1); + const view = new Uint8Array(buffer); view[0] = 0xff; mock.onGet("/").reply(200, buffer); @@ -951,7 +951,7 @@ describe("MockAdapter basics", function () { method: "GET", responseType: "arraybuffer", }).then(function (response) { - var view = new Uint8Array(response.data); + const view = new Uint8Array(response.data); expect(view[0]).to.equal(0xff); }); }); @@ -990,7 +990,7 @@ describe("MockAdapter basics", function () { expect(true).to.be.false; }) .catch(function (error) { - var serializableError = error.toJSON(); + const serializableError = error.toJSON(); expect(serializableError.message).to.equal( "Request failed with status code 404" ); diff --git a/test/cancelation.spec.js b/test/cancelation.spec.js index 5f733c4..ec9ec09 100644 --- a/test/cancelation.spec.js +++ b/test/cancelation.spec.js @@ -1,12 +1,12 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); -var CancelToken = axios.CancelToken; +const MockAdapter = require("../src"); +const CancelToken = axios.CancelToken; describe("MockAdapter basics", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -14,7 +14,7 @@ describe("MockAdapter basics", function () { }); it("handles canceled requests", function () { - var source = CancelToken.source(); + const source = CancelToken.source(); mock.onGet("/foo").reply(200); @@ -34,7 +34,7 @@ describe("MockAdapter basics", function () { }); it("works as normal is request is not canceled", function () { - var source = CancelToken.source(); + const source = CancelToken.source(); mock.onGet("/foo").reply(200); diff --git a/test/default_instance.spec.js b/test/default_instance.spec.js index 9dffb85..1bfd883 100644 --- a/test/default_instance.spec.js +++ b/test/default_instance.spec.js @@ -1,10 +1,10 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter on default axios instance", function () { - var mock; + let mock; beforeEach(function () { mock = new MockAdapter(axios); diff --git a/test/history.spec.js b/test/history.spec.js index fe6c3e3..238e89e 100644 --- a/test/history.spec.js +++ b/test/history.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter history", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); diff --git a/test/network_error.spec.js b/test/network_error.spec.js index 493fbc0..e7408e4 100644 --- a/test/network_error.spec.js +++ b/test/network_error.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("networkError spec", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); diff --git a/test/on_any.spec.js b/test/on_any.spec.js index f063624..5ccd7ed 100644 --- a/test/on_any.spec.js +++ b/test/on_any.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter onAny", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -41,7 +41,7 @@ describe("MockAdapter onAny", function () { }); it("mocks any request with a matching url and body", function () { - var body = [ + const body = [ { object: { with: { deep: "property" } }, array: ["1", "abc"] }, "a", ]; diff --git a/test/pass_through.spec.js b/test/pass_through.spec.js index 3c8d576..8f62570 100644 --- a/test/pass_through.spec.js +++ b/test/pass_through.spec.js @@ -1,15 +1,14 @@ -var axios = require("axios"); -var isLegacyAxios = require("axios/package.json").version[0] === "0"; -var expect = require("chai").expect; -var createServer = require("http").createServer; +const axios = require("axios"); +const expect = require("chai").expect; +const createServer = require("http").createServer; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("passThrough tests (requires Node)", function () { - var instance; - var mock; - var httpServer; - var serverUrl; + let instance; + let mock; + let httpServer; + let serverUrl; before("set up Node server", function () { return new Promise(function (resolve, reject) { @@ -24,7 +23,7 @@ describe("passThrough tests (requires Node)", function () { } }) .listen(0, "127.0.0.1", function () { - serverUrl = "http://127.0.0.1:" + httpServer.address().port; + serverUrl = `http://127.0.0.1:${httpServer.address().port}`; resolve(); }) .on("error", reject); @@ -87,16 +86,16 @@ describe("passThrough tests (requires Node)", function () { it("allows setting default passThrough handler", function () { mock.onGet("/foo").reply(200, "bar").onAny().passThrough(); - var randomPath = "xyz" + Math.round(10000 * Math.random()); + const randomPath = `xyz${Math.round(10000 * Math.random())}`; return Promise.all([ instance.get("/foo").then(function (response) { expect(response.status).to.equal(200); expect(response.data).to.equal("bar"); }), - instance.get("/" + randomPath).then(function (response) { + instance.get(`/${randomPath}`).then(function (response) { expect(response.status).to.equal(200); - expect(response.data).to.equal("/" + randomPath); + expect(response.data).to.equal(`/${randomPath}`); }), instance.post("/post").then(function (response) { expect(response.status).to.equal(200); @@ -107,7 +106,7 @@ describe("passThrough tests (requires Node)", function () { it("handles baseURL correctly", function () { instance = axios.create({ - baseURL: "/test", + baseURL: "http://localhost/test", proxy: { host: "127.0.0.1", port: httpServer.address().port, @@ -118,12 +117,7 @@ describe("passThrough tests (requires Node)", function () { mock.onAny().passThrough(); return instance.get("/foo").then(function (response) { expect(response.status).to.equal(200); - - if (isLegacyAxios) { - expect(response.data).to.equal("http://null/test/foo"); - } else { - expect(response.data).to.equal("http://localhost/test/foo"); - } + expect(response.data).to.equal("http://localhost/test/foo"); }); }); @@ -143,7 +137,7 @@ describe("passThrough tests (requires Node)", function () { data: "foo", transformRequest: [ function (data) { - return data + "foo"; + return `${data}foo`; }, ], }) @@ -159,7 +153,7 @@ describe("passThrough tests (requires Node)", function () { .get("/foo", { transformResponse: [ function (data) { - return data + "foo"; + return `${data}foo`; }, ], }) @@ -170,8 +164,8 @@ describe("passThrough tests (requires Node)", function () { it("applies interceptors only once", function () { mock.onGet("/foo").passThrough(); - var requestCount = 0; - var responseCount = 0; + let requestCount = 0; + let responseCount = 0; instance.interceptors.request.use(function (config) { requestCount++; return config; diff --git a/test/pass_through_on_no_match.spec.js b/test/pass_through_on_no_match.spec.js index 9e8d938..e7bc63a 100644 --- a/test/pass_through_on_no_match.spec.js +++ b/test/pass_through_on_no_match.spec.js @@ -1,15 +1,14 @@ -var axios = require("axios"); -var isLegacyAxios = require("axios/package.json").version[0] === "0"; -var expect = require("chai").expect; -var createServer = require("http").createServer; +const axios = require("axios"); +const expect = require("chai").expect; +const createServer = require("http").createServer; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("onNoMatch=passthrough option tests (requires Node)", function () { - var instance; - var mock; - var httpServer; - var serverUrl; + let instance; + let mock; + let httpServer; + let serverUrl; before("set up Node server", function () { return new Promise(function (resolve, reject) { @@ -24,7 +23,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { } }) .listen(0, "127.0.0.1", function () { - serverUrl = "http://127.0.0.1:" + httpServer.address().port; + serverUrl = `http://127.0.0.1:${httpServer.address().port}`; resolve(); }) .on("error", reject); @@ -41,12 +40,12 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { }); it("works correctly if set no handlers", function () { - var randomPath = "xyz" + Math.round(10000 * Math.random()); + const randomPath = `xyz${Math.round(10000 * Math.random())}`; return Promise.all([ - instance.get("/" + randomPath).then(function (response) { + instance.get(`/${randomPath}`).then(function (response) { expect(response.status).to.equal(200); - expect(response.data).to.equal("/" + randomPath); + expect(response.data).to.equal(`/${randomPath}`); }), ]); }); @@ -56,7 +55,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { mock.onGet("/error").reply(200, "success"); mock.onGet("/bar").passThrough(); - var randomPath = "xyz" + Math.round(10000 * Math.random()); + const randomPath = `xyz${Math.round(10000 * Math.random())}`; return Promise.all([ instance.get("/foo").then(function (response) { @@ -71,9 +70,9 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { expect(response.status).to.equal(200); expect(response.data).to.equal("/bar"); }), - instance.get("/" + randomPath).then(function (response) { + instance.get(`/${randomPath}`).then(function (response) { expect(response.status).to.equal(200); - expect(response.data).to.equal("/" + randomPath); + expect(response.data).to.equal(`/${randomPath}`); }), ]); }); @@ -93,16 +92,16 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { it("setting passThrough handler don't break anything", function () { mock.onGet("/foo").reply(200, "bar").onAny().passThrough(); - var randomPath = "xyz" + Math.round(10000 * Math.random()); + const randomPath = `xyz${Math.round(10000 * Math.random())}`; return Promise.all([ instance.get("/foo").then(function (response) { expect(response.status).to.equal(200); expect(response.data).to.equal("bar"); }), - instance.get("/" + randomPath).then(function (response) { + instance.get(`/${randomPath}`).then(function (response) { expect(response.status).to.equal(200); - expect(response.data).to.equal("/" + randomPath); + expect(response.data).to.equal(`/${randomPath}`); }), instance.post("/post").then(function (response) { expect(response.status).to.equal(200); @@ -113,7 +112,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { it("handles baseURL correctly", function () { instance = axios.create({ - baseURL: "/test", + baseURL: "http://localhost/test", proxy: { host: "127.0.0.1", port: httpServer.address().port, @@ -123,11 +122,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { return instance.get("/foo").then(function (response) { expect(response.status).to.equal(200); - if (isLegacyAxios) { - expect(response.data).to.equal("http://null/test/foo"); - } else { - expect(response.data).to.equal("http://localhost/test/foo"); - } + expect(response.data).to.equal("http://localhost/test/foo"); }); }); @@ -137,7 +132,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { data: "foo", transformRequest: [ function (data) { - return data + "foo"; + return `${data}foo`; }, ], }) @@ -151,7 +146,7 @@ describe("onNoMatch=passthrough option tests (requires Node)", function () { .get("/foo", { transformResponse: [ function (data) { - return data + "foo"; + return `${data}foo`; }, ], }) diff --git a/test/promise.spec.js b/test/promise.spec.js index 3d1cfc4..c6a69ce 100644 --- a/test/promise.spec.js +++ b/test/promise.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter reply with Promise", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -51,6 +51,7 @@ describe("MockAdapter reply with Promise", function () { it("passes rejecting Promise verbatim", function () { mock.onGet("/reject").reply(function () { return new Promise(function (resolve, reject) { + // eslint-disable-next-line prefer-promise-reject-errors reject({ custom: "error" }); }); }); diff --git a/test/reply_once.spec.js b/test/reply_once.spec.js index 2c5a302..f3c0039 100644 --- a/test/reply_once.spec.js +++ b/test/reply_once.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("MockAdapter replyOnce", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -37,7 +37,7 @@ describe("MockAdapter replyOnce", function () { }); it("replies only once", function () { - var called = false; + let called = false; mock.onGet("/foo").replyOnce(200); return instance @@ -53,7 +53,7 @@ describe("MockAdapter replyOnce", function () { }); it("replies only once when used with onAny", function () { - var called = false; + let called = false; mock.onAny("/foo").replyOnce(200); return instance @@ -69,8 +69,8 @@ describe("MockAdapter replyOnce", function () { }); it("replies only once when using request body matching", function () { - var called = false; - var body = "abc"; + let called = false; + const body = "abc"; mock.onPost("/onceWithBody", body).replyOnce(200); return instance diff --git a/test/throw_exception_on_no_match.spec.js b/test/throw_exception_on_no_match.spec.js index 0196e5b..ed52adb 100644 --- a/test/throw_exception_on_no_match.spec.js +++ b/test/throw_exception_on_no_match.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("onNoMatch=throwException option tests (requires Node)", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -29,8 +29,8 @@ describe("onNoMatch=throwException option tests (requires Node)", function () { }); it("handles errors correctly when could not find mock for requested url", function () { - var expectedUrl = "http://127.0.0.1/unexistent_path"; - var expectedMethod = "get"; + const expectedUrl = "http://127.0.0.1/unexistent_path"; + const expectedMethod = "get"; return instance .get(expectedUrl) diff --git a/test/timeout.spec.js b/test/timeout.spec.js index 4745deb..989ace2 100644 --- a/test/timeout.spec.js +++ b/test/timeout.spec.js @@ -1,11 +1,11 @@ -var axios = require("axios"); -var expect = require("chai").expect; +const axios = require("axios"); +const expect = require("chai").expect; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("timeout spec", function () { - var instance; - var mock; + let instance; + let mock; beforeEach(function () { instance = axios.create(); @@ -46,7 +46,7 @@ describe("timeout spec", function () { it("responds with timeoutErrorMessage", function () { mock.onGet("/foo").timeout(); - var timeoutErrorMessage = "That request sure did time out"; + const timeoutErrorMessage = "That request sure did time out"; return instance .get("/foo", { diff --git a/test/trailing_slash_baseurl.spec.js b/test/trailing_slash_baseurl.spec.js index ebbbac2..19aa77d 100644 --- a/test/trailing_slash_baseurl.spec.js +++ b/test/trailing_slash_baseurl.spec.js @@ -1,14 +1,14 @@ -var axios = require("axios"); -var expect = require("chai").expect; -var createServer = require("http").createServer; +const axios = require("axios"); +const expect = require("chai").expect; +const createServer = require("http").createServer; -var MockAdapter = require("../src"); +const MockAdapter = require("../src"); describe("trailing slash in axios baseUrl issue (requires Node)", function () { - var instance; - var mock; - var httpServer; - var serverUrl; + let instance; + let mock; + let httpServer; + let serverUrl; before("set up Node server", function () { return new Promise(function (resolve, reject) { @@ -23,7 +23,7 @@ describe("trailing slash in axios baseUrl issue (requires Node)", function () { } }) .listen(0, "127.0.0.1", function () { - serverUrl = "http://127.0.0.1:" + httpServer.address().port; + serverUrl = `http://127.0.0.1:${httpServer.address().port}`; resolve(); }) .on("error", reject); @@ -35,7 +35,7 @@ describe("trailing slash in axios baseUrl issue (requires Node)", function () { }); beforeEach(function () { - instance = axios.create({ baseURL: serverUrl + "/" }); // baseUrl has a trailing slash + instance = axios.create({ baseURL: `${serverUrl}/` }); // baseUrl has a trailing slash mock = new MockAdapter(instance); }); diff --git a/test/utils.spec.js b/test/utils.spec.js index 62fbdd7..d52bff9 100644 --- a/test/utils.spec.js +++ b/test/utils.spec.js @@ -1,34 +1,34 @@ -var expect = require("chai").expect; -var find = require("../src/utils").find; -var isEqual = require("../src/utils").isEqual; -var isObjectOrArray = require("../src/utils").isObjectOrArray; -var isBlob = require("../src/utils").isBlob; -var isBodyOrParametersMatching = require("../src/utils").isBodyOrParametersMatching; +const expect = require("chai").expect; +const find = require("../src/utils").find; +const isEqual = require("../src/utils").isEqual; +const isObjectOrArray = require("../src/utils").isObjectOrArray; +const isBlob = require("../src/utils").isBlob; +const isBodyOrParametersMatching = require("../src/utils").isBodyOrParametersMatching; describe("utility functions", function () { context("find", function () { it("returns the value for which the predicate holds true", function () { - var array = [1, 2, 3]; - var value = find(array, function (value) { + const array = [1, 2, 3]; + const value = find(array, function (value) { return value === 2; }); expect(value).to.equal(2); }); it("returns the first value for which the predicate holds true", function () { - var array = [ + const array = [ { key: 1, value: "one" }, { key: 1, value: "two" }, ]; - var value = find(array, function (value) { + const value = find(array, function (value) { return value.key === 1; }); expect(value.value).to.equal("one"); }); it("returns undefined if the value is not found", function () { - var array = [1, 2, 3]; - var value = find(array, function (value) { + const array = [1, 2, 3]; + const value = find(array, function (value) { return value === 4; }); expect(value).to.be.undefined; @@ -37,8 +37,8 @@ describe("utility functions", function () { context("isEqual", function () { it("checks with strict equality", function () { - var a = { foo: "5" }; - var b = { foo: 5 }; + const a = { foo: "5" }; + const b = { foo: 5 }; expect(isEqual(a, b)).to.be.false; }); }); @@ -84,18 +84,18 @@ describe("utility functions", function () { }); context("isBodyOrParametersMatching", function() { - it('delete has params only', function () { - expect(isBodyOrParametersMatching(null, { 'a': 2 }, { 'params': { 'a': 2 } } )).to.be.true; - expect(isBodyOrParametersMatching(null, { 'a': 2 }, { 'params': { 'b': 2 } } )).to.be.false; + it("delete has params only", function () { + expect(isBodyOrParametersMatching(null, { "a": 2 }, { "params": { "a": 2 } } )).to.be.true; + expect(isBodyOrParametersMatching(null, { "a": 2 }, { "params": { "b": 2 } } )).to.be.false; }); - it('delete has data only', function () { - expect(isBodyOrParametersMatching({ 'x': 1 }, null, { 'data': { 'x': 1 } })).to.be.true; - expect(isBodyOrParametersMatching({ 'x': 1 }, null, { 'data': { 'y': 1 } })).to.be.false; + it("delete has data only", function () { + expect(isBodyOrParametersMatching({ "x": 1 }, null, { "data": { "x": 1 } })).to.be.true; + expect(isBodyOrParametersMatching({ "x": 1 }, null, { "data": { "y": 1 } })).to.be.false; }); - it('delete has body and params', function () { - expect(isBodyOrParametersMatching({ 'x': 1 }, { 'a': 2 }, { 'data': { 'x': 1 }, 'params': { 'a': 2 } })).to.be.true; - expect(isBodyOrParametersMatching({ 'x': 1 }, { 'a': 2 }, { 'data': { 'x': 1 }, 'params': { 'b': 2 } })).to.be.false; - expect(isBodyOrParametersMatching({ 'x': 1 }, { 'a': 2 }, { 'data': { 'y': 1 }, 'params': { 'a': 2 } })).to.be.false; + it("delete has body and params", function () { + expect(isBodyOrParametersMatching({ "x": 1 }, { "a": 2 }, { "data": { "x": 1 }, "params": { "a": 2 } })).to.be.true; + expect(isBodyOrParametersMatching({ "x": 1 }, { "a": 2 }, { "data": { "x": 1 }, "params": { "b": 2 } })).to.be.false; + expect(isBodyOrParametersMatching({ "x": 1 }, { "a": 2 }, { "data": { "y": 1 }, "params": { "a": 2 } })).to.be.false; }); }); }); diff --git a/types/index.d.ts b/types/index.d.ts index d6038d3..01f0ec8 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,13 +1,32 @@ import { AxiosAdapter, AxiosInstance, AxiosRequestConfig } from 'axios'; +interface AxiosHeaders { + [key: string]: string | number | boolean | null | undefined; +} + +type MockArrayResponse = [ + status: number, + data?: any, + headers?: AxiosHeaders +]; + +type MockObjectResponse = { + status: number; + data: any; + headers?: AxiosHeaders, + config?: AxiosRequestConfig +}; + +type MockResponse = MockArrayResponse | MockObjectResponse; + type CallbackResponseSpecFunc = ( config: AxiosRequestConfig -) => any[] | Promise; +) => MockResponse | Promise; type ResponseSpecFunc = ( statusOrCallback: number | CallbackResponseSpecFunc, data?: T, - headers?: any + headers?: AxiosHeaders ) => MockAdapter; declare namespace MockAdapter { @@ -64,6 +83,20 @@ type NoBodyRequestMatcherFunc = ( config?: ConfigMatcher ) => MockAdapter.RequestHandler; +type verb = + | 'get' + | 'post' + | 'put' + | 'delete' + | 'patch' + | 'options' + | 'head' + | 'list' + | 'link' + | 'unlink'; + +type HistoryArray = AxiosRequestConfig[] & Record + declare class MockAdapter { static default: typeof MockAdapter; @@ -75,7 +108,7 @@ declare class MockAdapter { resetHistory(): void; restore(): void; - history: { [method: string]: AxiosRequestConfig[] }; + history: HistoryArray; onAny: NoBodyRequestMatcherFunc; onGet: NoBodyRequestMatcherFunc; diff --git a/types/test.ts b/types/test.ts index 4d4cb01..a0a8caf 100644 --- a/types/test.ts +++ b/types/test.ts @@ -38,6 +38,21 @@ namespace SupportsResetHistory { mock.resetHistory(); } +namespace SupportsHistoryArray { + mock.history.length; + mock.history[0].method; + mock.history[0].url; + mock.history[0].params; + mock.history[0].data; + mock.history[0].headers; + + mock.history.get[0].method; + mock.history.get[0].url; + mock.history.get[0].params; + mock.history.get[0].data; + mock.history.get[0].headers; +} + namespace SupportsRestore { mock.restore(); }