From ccfde9490f9c622fe841b1e588769f47962f6b25 Mon Sep 17 00:00:00 2001 From: StEve Young <2747745470@qq.com> Date: Mon, 28 Oct 2019 02:48:53 -0500 Subject: [PATCH] fix(jsonp, config): fix callbackName, host -> baseUrl (#43) * fix(jsonp, config): fix callbackName, host -> baseUrl * refactor: use axios once * fix(utils): encode key and value both * chore: update deps, add all-contributors * docs: display contributors * fix(utils): use empty string to avoid error * fix: make it compatible with [host] --- .all-contributorsrc | 36 ++++++++++++++++++++++++++ README.md | 33 +++++++++++++++++++----- docs/README.md | 21 ++++++++++++++++ docs/config/common.md | 7 ++++-- docs/config/default.md | 5 +++- docs/guide/README.md | 12 ++++----- docs/guide/middleware.md | 3 ++- examples/apis-mp/fake-wx.js | 2 +- examples/apis-web/fake-get.js | 2 +- examples/apis-web/fake-post.js | 12 ++++----- jest.config.js | 16 ++++++++++++ package.json | 45 +++++++++++---------------------- src/adapters/axios.js | 2 +- src/index.d.ts | 13 ++++++++-- src/index.js | 46 +++++++++++++++++++++++----------- src/middlewareFns.js | 5 ++-- src/utils/combineUrls.js | 19 ++++++++++++++ src/utils/index.js | 1 + src/utils/params.js | 2 +- test/__tests__/axios.test.js | 12 ++++----- test/__tests__/utils.test.js | 13 ++++++++++ test/__tests__/wx.test.js | 18 ++++++++++++- 22 files changed, 244 insertions(+), 81 deletions(-) create mode 100644 .all-contributorsrc create mode 100644 jest.config.js create mode 100644 src/utils/combineUrls.js diff --git a/.all-contributorsrc b/.all-contributorsrc new file mode 100644 index 0000000..5ecff6d --- /dev/null +++ b/.all-contributorsrc @@ -0,0 +1,36 @@ +{ + "projectName": "tua-api", + "projectOwner": "tuateam", + "repoType": "github", + "repoHost": "https://github.com", + "files": [ + "README.md", + "docs/README.md" + ], + "imageSize": 100, + "commit": true, + "commitConvention": "angular", + "contributors": [ + { + "login": "BuptStEve", + "name": "StEve Young", + "avatar_url": "https://avatars2.githubusercontent.com/u/11501493?v=4", + "profile": "https://buptsteve.github.io", + "contributions": [ + "code", + "doc", + "infra" + ] + }, + { + "login": "evinma", + "name": "evinma", + "avatar_url": "https://avatars2.githubusercontent.com/u/16096567?v=4", + "profile": "https://github.com/evinma", + "contributions": [ + "code" + ] + } + ], + "contributorsPerLine": 7 +} diff --git a/README.md b/README.md index ed6689f..6e35e6f 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Downloads per month Version + Next Version License

@@ -137,8 +138,8 @@ tuaStorage ### 地址结构划分 以上地址,一般将其分为`3`部分: -* host: `'https://example-base.com/'` -* prefix: `'foo/bar/something'` +* baseUrl: `'https://example-base.com/foo/bar'` +* prefix: `'something'` * pathList: `[ 'create', 'modify', 'delete' ]` ### 文件结构 @@ -158,11 +159,11 @@ tuaStorage // src/apis/something.js export default { - // 请求的公用服务器地址 - host: 'https://example-base.com/', + // 接口基础地址 + baseUrl: 'https://example-base.com/foo/bar', - // 请求的中间路径 - prefix: 'foo/bar/something', + // 接口的中间路径 + prefix: 'something', // 接口地址数组 pathList: [ @@ -223,3 +224,23 @@ $ tuamp add api

👉更多配置点击这里👈

+ +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + +
StEve Young
StEve Young

💻 📖 🚇
evinma
evinma

💻
+ + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/docs/README.md b/docs/README.md index a700a2c..a9507fc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -37,6 +37,27 @@ footer: MIT Licensed | Copyright © 2018-present StEve Young Downloads per month Version + Next Version License

+ +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + +
StEve Young
StEve Young

💻 📖 🚇
evinma
evinma

💻
+ + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/docs/config/common.md b/docs/config/common.md index 3a4e0a8..eefb8d4 100644 --- a/docs/config/common.md +++ b/docs/config/common.md @@ -14,10 +14,13 @@ export default { } ``` -## host 服务器地址 +## host 接口基础地址 +重命名为 `baseUrl`,`host` 属性将在 `2.0.0+` 后废弃。 + +## baseUrl 接口基础地址 ```js export default { - host: 'https://example-api.com/', + baseUrl: 'https://example-api.com/', } ``` diff --git a/docs/config/default.md b/docs/config/default.md index e090ed7..8ba83d7 100644 --- a/docs/config/default.md +++ b/docs/config/default.md @@ -14,7 +14,10 @@ new TuaApi({ }) ``` -## host 服务器基础地址 +## host 接口基础地址 +重命名为 `baseUrl`,`host` 属性将在 `2.0.0+` 后废弃。 + +## baseUrl 接口基础地址 例如 `https://example.com/api/` ## reqType 请求类型 diff --git a/docs/guide/README.md b/docs/guide/README.md index 6c1ec3e..51c0fb7 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -69,8 +69,8 @@ tuaStorage ### 地址结构划分 以上地址,一般将其分为`3`部分: -* host: `'https://example-base.com/'` -* prefix: `'foo/bar/something'` +* baseUrl: `'https://example-base.com/foo/bar'` +* prefix: `'something'` * pathList: `[ 'create', 'modify', 'delete' ]` ### 文件结构 @@ -90,11 +90,11 @@ tuaStorage // src/apis/something.js export default { - // 请求的公用服务器地址 - host: 'https://example-base.com/', + // 接口基础地址 + baseUrl: 'https://example-base.com/foo/bar', - // 请求的中间路径 - prefix: 'foo/bar/something', + // 接口的中间路径 + prefix: 'something', // 接口地址数组 pathList: [ diff --git a/docs/guide/middleware.md b/docs/guide/middleware.md index 8e90af6..664656d 100644 --- a/docs/guide/middleware.md +++ b/docs/guide/middleware.md @@ -53,7 +53,8 @@ async function (ctx, next) { | 已使用的属性名 | 含义和作用 | | --- | --- | | req | 请求 | -| req.host | 服务器地址 | +| req.host | 接口基础地址 | +| req.baseUrl | 接口基础地址 | | req.mock | 模拟的响应数据或是生成数据的函数 | | req.type | 接口请求类型 get/post... | | req.method | 接口请求类型 get/post... | diff --git a/examples/apis-mp/fake-wx.js b/examples/apis-mp/fake-wx.js index 867ef96..f6f8789 100644 --- a/examples/apis-mp/fake-wx.js +++ b/examples/apis-mp/fake-wx.js @@ -1,6 +1,6 @@ export default { // 该参数表示请求的公用服务器地址。 - host: 'http://example-base.com/', + baseUrl: 'http://example-base.com/', // 该参数表示请求的中间路径,建议与文件同名,以便后期维护。 prefix: 'fake-wx', diff --git a/examples/apis-web/fake-get.js b/examples/apis-web/fake-get.js index b2f9f18..bce5879 100644 --- a/examples/apis-web/fake-get.js +++ b/examples/apis-web/fake-get.js @@ -1,6 +1,6 @@ export default { // 请求的公用服务器地址。 - // host: 'http://example-base.com/', + // baseUrl: 'http://example-base.com/', // 请求的中间路径,建议与文件同名,以便后期维护。 prefix: 'fake-get', diff --git a/examples/apis-web/fake-post.js b/examples/apis-web/fake-post.js index 5af9adb..afd0985 100644 --- a/examples/apis-web/fake-post.js +++ b/examples/apis-web/fake-post.js @@ -1,6 +1,6 @@ export default { // 该参数表示请求的公用服务器地址。 - host: 'http://example-base.com/', + baseUrl: 'http://example-base.com/', // 该参数表示请求的中间路径,建议与文件同名,以便后期维护。 prefix: 'fake-post', @@ -34,7 +34,7 @@ export default { params: ['param1', 'param2'], }, /** - * array-params with new host + * array-params with new baseUrl */ { name: 'hap', @@ -43,7 +43,7 @@ export default { reqType: ('axios'), middleware: [ async (ctx, next) => { - ctx.req.host = 'http://custom-host.com/' + ctx.req.baseUrl = 'http://custom-baseUrl.com/' await next() }, ], @@ -61,12 +61,12 @@ export default { }, }, /** - * own-host + * own-baseUrl */ { name: 'oh', - path: 'own-host', - host: 'http://example-test.com/', + path: 'own-baseUrl', + baseUrl: 'http://example-test.com/', params: {}, // 表示这个接口不需要传递 commonParams commonParams: null, diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..bb7e48c --- /dev/null +++ b/jest.config.js @@ -0,0 +1,16 @@ +module.exports = { + bail: true, + clearMocks: true, + transform: { + '^.+\\.js$': 'babel-jest', + }, + moduleNameMapper: { + '@/(.*)$': '/src/$1', + '@examples/(.*)$': '/examples/$1', + }, + collectCoverage: true, + collectCoverageFrom: [ + 'src/**', + '!src/index.d.ts', + ], +} diff --git a/package.json b/package.json index db5cfdb..d8a1b9c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tua-api", - "version": "1.4.0", + "version": "1.4.1", "description": "🏗 A common tool helps converting configs to api functions", "main": "dist/TuaApi.cjs.js", "module": "dist/TuaApi.esm.js", @@ -40,22 +40,6 @@ "git add" ] }, - "jest": { - "bail": true, - "clearMocks": true, - "transform": { - "^.+\\.js$": "babel-jest" - }, - "moduleNameMapper": { - "@/(.*)$": "/src/$1", - "@examples/(.*)$": "/examples/$1" - }, - "collectCoverage": true, - "collectCoverageFrom": [ - "src/**", - "!src/index.d.ts" - ] - }, "eslintIgnore": [ "dist/*", "!.eslintrc.js", @@ -67,32 +51,33 @@ "koa-compose": "^4.1.0" }, "devDependencies": { - "@babel/core": "^7.6.2", + "@babel/core": "^7.6.4", "@babel/plugin-external-helpers": "^7.2.0", "@babel/plugin-proposal-decorators": "^7.6.0", - "@babel/plugin-proposal-object-rest-spread": "^7.5.5", - "@babel/preset-env": "^7.6.0", - "@commitlint/cli": "^8.1.0", - "@commitlint/config-conventional": "^8.1.0", + "@babel/plugin-proposal-object-rest-spread": "^7.6.2", + "@babel/preset-env": "^7.6.3", + "@commitlint/cli": "^8.2.0", + "@commitlint/config-conventional": "^8.2.0", "@types/jest": "^24.0.18", + "all-contributors-cli": "^6.9.1", "axios-mock-adapter": "^1.17.0", "babel-core": "^7.0.0-bridge.0", "babel-eslint": "^10.0.3", "babel-jest": "^24.9.0", - "codecov": "^3.5.0", - "cross-env": "^5.2.1", - "eslint": "^6.3.0", + "codecov": "^3.6.1", + "cross-env": "^6.0.3", + "eslint": "^6.5.1", "eslint-config-standard": "^14.1.0", "eslint-plugin-import": "^2.18.2", "eslint-plugin-node": "^10.0.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.1", "gh-pages": "^2.1.1", - "husky": "^3.0.5", + "husky": "^3.0.8", "jest": "^24.9.0", - "lint-staged": "^9.2.5", + "lint-staged": "^9.4.2", "rimraf": "^3.0.0", - "rollup": "^1.21.2", + "rollup": "^1.23.1", "rollup-plugin-babel": "^4.3.3", "rollup-plugin-commonjs": "^10.1.0", "rollup-plugin-eslint": "^7.0.0", @@ -100,8 +85,8 @@ "rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-replace": "^2.2.0", "rollup-plugin-uglify": "^6.0.3", - "typescript": "^3.6.3", - "vuepress": "^1.0.4" + "typescript": "^3.6.4", + "vuepress": "^1.1.0" }, "repository": { "type": "git", diff --git a/src/adapters/axios.js b/src/adapters/axios.js index 5a62c7d..4fcddb2 100644 --- a/src/adapters/axios.js +++ b/src/adapters/axios.js @@ -10,7 +10,7 @@ import { logger, isFormData, getParamStrFromObj } from '../utils' export const getAxiosPromise = ({ url, data, - method = 'post', + method, headers = DEFAULT_HEADER, crossDomain = true, withCredentials = true, diff --git a/src/index.d.ts b/src/index.d.ts index 3f36271..099af9e 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -46,11 +46,14 @@ export interface ParamsObject { } export interface CtxReq { + // deprecated host: string - mock: Mock + baseUrl: string // deprecated type: Method method: Method + + mock: Mock path: string prefix: string reqType: ReqType @@ -77,11 +80,14 @@ export interface Ctx { } export interface BaseApiConfig { - mock?: Mock + // deprecated host?: string + baseUrl?: string // deprecated type?: Method method?: Method + + mock?: Mock prefix?: string reqType?: ReqType afterFn?: (args: [U?, Ctx?]) => Promise @@ -132,7 +138,10 @@ export interface SyncFnMap { [k: string]: Api } export interface TuaApiClass { new (args?: { + // deprecated host?: string + baseUrl?: string + reqType?: string middleware?: Middleware[] axiosOptions?: AxiosOptions diff --git a/src/index.js b/src/index.js index c58698c..06f7d41 100644 --- a/src/index.js +++ b/src/index.js @@ -33,6 +33,7 @@ class TuaApi { /** * @param {object} [options] * @param {string} [options.host] 服务器基础地址,例如 https://example.com/ + * @param {string} [options.baseUrl] 服务器基础地址,例如 https://example.com/ * @param {string} [options.reqType] 使用什么工具发(axios/jsonp/wx) * @param {function[]} [options.middleware] 中间件函数数组 * @param {object} [options.axiosOptions] 透传 axios 配置参数 @@ -41,13 +42,14 @@ class TuaApi { */ constructor ({ host, + baseUrl = host, reqType = isWx() ? 'wx' : 'axios', middleware = [], axiosOptions = {}, jsonpOptions = {}, defaultErrorData = { code: 999, msg: '出错啦!' }, } = {}) { - this.host = host + this.baseUrl = baseUrl this.reqType = reqType this.middleware = middleware this.axiosOptions = axiosOptions @@ -56,6 +58,13 @@ class TuaApi { this._checkReqType(this.reqType) + if (host) { + logger.warn( + '[host] will be deprecated, please use [baseUrl] instead!\n' + + '[host] 属性将被废弃, 请用 [baseUrl] 替代!' + ) + } + return this } @@ -113,7 +122,7 @@ class TuaApi { fullUrl, reqType, reqParams: data, - callbackName, + callbackName: jsonpCallbackFunction, axiosOptions, jsonpOptions, ...rest @@ -136,7 +145,7 @@ class TuaApi { return getWxPromise({ url, fullUrl, data, method, header, ...rest }) } - if (reqType === 'axios') { + if (reqType === 'axios' || method === 'post') { const params = { ...axiosOptions, url: method === 'get' ? fullUrl : url, @@ -148,13 +157,10 @@ class TuaApi { return getAxiosPromise(params) } - // 对于 post 请求使用 axios - return method === 'post' - ? getAxiosPromise({ url, data, ...axiosOptions }) - : getFetchJsonpPromise({ - url: fullUrl, - jsonpOptions: { ...jsonpOptions, callbackName }, - }) + return getFetchJsonpPromise({ + url: fullUrl, + jsonpOptions: { ...jsonpOptions, jsonpCallbackFunction }, + }) } /** @@ -216,7 +222,7 @@ class TuaApi { * @param {function} options.beforeFn 在请求发起前执行的钩子函数(将被废弃) * @param {function[]} options.middleware 中间件函数数组 * @param {Boolean} options.useGlobalMiddleware 是否使用全局中间件 - * @param {string} options.host 服务器地址 + * @param {string} options.baseUrl 服务器地址 * @param {string} options.reqType 使用什么工具发 * @param {object} options.axiosOptions 透传 axios 配置参数 * @param {object} options.jsonpOptions 透传 fetch-jsonp 配置参数 @@ -251,7 +257,7 @@ class TuaApi { type = method // 合并全局默认值 - rest.host = rest.host || this.host + rest.baseUrl = rest.baseUrl || this.baseUrl rest.reqType = rest.reqType || this.reqType rest.axiosOptions = rest.axiosOptions ? { ...this.axiosOptions, ...rest.axiosOptions } @@ -270,10 +276,22 @@ class TuaApi { args = args || {} // 最终的运行时配置,runtimeOptions 有最高优先级 - const runtimeParams = { type, path, params, prefix, apiName, fullPath: `${prefix}/${path}`, ...rest, ...runtimeOptions } + const runtimeParams = { + type, + path, + params, + prefix, + apiName, + fullPath: `${prefix}/${path}`, + ...rest, + ...runtimeOptions, + } // 向前兼容 - runtimeParams.method = runtimeParams.type + runtimeParams.host = runtimeParams.host || runtimeParams.baseUrl + runtimeParams.baseUrl = runtimeParams.baseUrl || runtimeParams.host + + runtimeParams.method = runtimeParams.method || runtimeParams.type // 自定义回调函数名称(用于 jsonp) runtimeParams.callbackName = runtimeParams.callbackName || `${runtimeParams.path}Callback` diff --git a/src/middlewareFns.js b/src/middlewareFns.js index 56ce2d7..70da86b 100644 --- a/src/middlewareFns.js +++ b/src/middlewareFns.js @@ -1,6 +1,7 @@ import { ERROR_STRINGS } from './constants' import { isFormData, + combineUrls, checkArrayParams, getParamStrFromObj, getDefaultParamObj, @@ -86,10 +87,10 @@ const formatReqParamsMiddleware = (ctx, next) => { * @param {Function} next 转移控制权给下一个中间件的函数 */ const setReqFnParamsMiddleware = (ctx, next) => { - const { path, host, prefix, reqParams, ...rest } = ctx.req + const { path, prefix, reqParams, baseUrl, ...rest } = ctx.req // 请求地址 - const url = host + prefix + '/' + path + const url = combineUrls(combineUrls(baseUrl, prefix), path) const paramsStr = getParamStrFromObj(reqParams) // 完整请求地址,将参数拼在 url 上,用于 get 请求 const fullUrl = paramsStr ? `${url}?${paramsStr}` : url diff --git a/src/utils/combineUrls.js b/src/utils/combineUrls.js new file mode 100644 index 0000000..46ca644 --- /dev/null +++ b/src/utils/combineUrls.js @@ -0,0 +1,19 @@ +/** + * Creates a new URL by combining the specified URLs + * @param {string} baseUrl The base URL + * @param {string} relativeUrl The relative URL + * @returns {string} The combined URL + */ +function combineUrls (baseUrl = '', relativeUrl = '') { + if (!relativeUrl) return baseUrl + + return ( + baseUrl.replace(/\/+$/, '') + + '/' + + relativeUrl.replace(/^\/+/, '') + ) +} + +export { + combineUrls, +} diff --git a/src/utils/index.js b/src/utils/index.js index 31aefa7..6f26c9e 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -3,3 +3,4 @@ export * from './mp' export * from './judge' export * from './logger' export * from './params' +export * from './combineUrls' diff --git a/src/utils/params.js b/src/utils/params.js index 21b6d51..0edb4d0 100644 --- a/src/utils/params.js +++ b/src/utils/params.js @@ -15,7 +15,7 @@ import { ERROR_STRINGS } from '../constants' */ const getParamStrFromObj = (data = {}) => pipe( Object.keys, - map(key => `${key}=${encodeURIComponent(data[key])}`), + map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`), join('&') )(data) diff --git a/test/__tests__/axios.test.js b/test/__tests__/axios.test.js index 321a75c..693b254 100644 --- a/test/__tests__/axios.test.js +++ b/test/__tests__/axios.test.js @@ -14,16 +14,16 @@ const params = { const reqAPUrl = 'http://example-base.com/fake-post/array-params' const reqOPUrl = 'http://example-base.com/fake-post/object-params' const reqGOPUrl = 'http://example-base.com/fake-get/object-params' -const reqOHUrl = 'http://example-test.com/fake-post/own-host' +const reqOHUrl = 'http://example-test.com/fake-post/own-baseUrl' const reqTAUrl = 'http://example-base.com/fake-get/req-type-axios?asyncCp=asyncCp' const reqEAPUrl = 'http://example-base.com/fake-post/empty-array-params' const reqMFDUrl = 'http://example-base.com/fake-get/mock-function-data' const reqBFCUrl = 'http://example-base.com/fake-get/beforeFn-cookie' describe('middleware', () => { - test('change host before request', async () => { - const data = { code: 0, data: 'custom host' } - const reqHAPUrl = 'http://custom-host.com/fake-post/array-params' + test('change baseUrl before request', async () => { + const data = { code: 0, data: 'custom baseUrl' } + const reqHAPUrl = 'http://custom-baseUrl.com/fake-post/array-params' mock.onPost(reqHAPUrl).reply(200, data) const resData = await fakePostApi.hap() @@ -115,8 +115,8 @@ describe('fake post requests', () => { mock.resetHistory() }) - test('own-host', async () => { - const data = { code: 0, data: 'own-host' } + test('own-baseUrl', async () => { + const data = { code: 0, data: 'own-baseUrl' } mock.onPost(reqOHUrl).reply(200, data) const resData = await fakePostApi.oh() diff --git a/test/__tests__/utils.test.js b/test/__tests__/utils.test.js index 60452f4..a885bd4 100644 --- a/test/__tests__/utils.test.js +++ b/test/__tests__/utils.test.js @@ -1,5 +1,6 @@ import { ERROR_STRINGS } from '@/constants' import { + combineUrls, promisifyWxApi, checkArrayParams, getDefaultParamObj, @@ -7,6 +8,17 @@ import { apiConfigToReqFnParams, } from '@/utils' +test('combineUrls', () => { + expect(combineUrls(undefined, undefined)).toBe('') + expect(combineUrls(undefined, 'users')).toBe('/users') + expect(combineUrls('https://api.github.com', undefined)).toBe('https://api.github.com') + expect(combineUrls('https://api.github.com', 'users')).toBe('https://api.github.com/users') + expect(combineUrls('https://api.github.com', '/users')).toBe('https://api.github.com/users') + expect(combineUrls('https://api.github.com/', '/users')).toBe('https://api.github.com/users') + expect(combineUrls('https://api.github.com/users', '')).toBe('https://api.github.com/users') + expect(combineUrls('https://api.github.com/users', '/')).toBe('https://api.github.com/users/') +}) + test('promisifyWxApi', () => { const fn = ({ success }) => setTimeout(() => success('test'), 0) const promisifiedFn = promisifyWxApi(fn) @@ -58,6 +70,7 @@ test('getParamStrFromObj', () => { expect(getParamStrFromObj({})).toBe('') expect(getParamStrFromObj({ a: 1, b: 2 })).toBe('a=1&b=2') expect(getParamStrFromObj({ a: 1, b: 2, c: '哈喽' })).toBe('a=1&b=2&c=%E5%93%88%E5%96%BD') + expect(getParamStrFromObj({ 哈喽: '哈喽' })).toBe('%E5%93%88%E5%96%BD=%E5%93%88%E5%96%BD') }) test('apiConfigToReqFnParams', () => { diff --git a/test/__tests__/wx.test.js b/test/__tests__/wx.test.js index 9a879c9..ad700bd 100644 --- a/test/__tests__/wx.test.js +++ b/test/__tests__/wx.test.js @@ -55,10 +55,26 @@ describe('middleware', () => { const tuaApi = new TuaApi() const fakeWxApi = tuaApi.getApi(fakeWx) const globalMiddlewareFn = jest.fn(async (ctx, next) => { + expect(ctx.req.host).toBeDefined() + expect(ctx.req.baseUrl).toBeDefined() + expect(ctx.req.type).toBeDefined() + expect(ctx.req.method).toBeDefined() + expect(ctx.req.path).toBeDefined() + expect(ctx.req.prefix).toBeDefined() + expect(ctx.req.reqType).toBeDefined() + expect(ctx.req.reqParams).toBeDefined() + expect(ctx.req.callbackName).toBeDefined() + expect(ctx.req.axiosOptions).toBeDefined() + expect(ctx.req.jsonpOptions).toBeDefined() + expect(ctx.req.reqFnParams).toBeDefined() + await next() - expect(ctx.endTime).toBeDefined() expect(ctx.reqTime).toBeDefined() + expect(ctx.startTime).toBeDefined() + expect(ctx.endTime).toBeDefined() + + expect(ctx.res.data).toBeDefined() }) tuaApi.use(globalMiddlewareFn)