名称 | 地址 | 安装 |
---|---|---|
Mock.js | https://github.com/nuysoft/Mock | npm install mockjs |
mockm | https://github.com/wll8/mockm | npm install mockm |
JSON Server | https://github.com/typicode/json-server | npm install json-server |
MSW(Mock Service Worker) | https://github.com/mswjs/msw | npm install msw |
Mirage JS | https://github.com/miragejs/miragejs | npm install miragejs |
Mirage JS
特性:
- 复写
fetch
和XMLHttpRequest
实现拦截,所以在 Dev Tools 中的 Network 是看不到请求的。 - 默认全部拦截,直通函数
passthrough
匹配不太友好。
使用它主要是因为不用配置代理,也不用单独去启动一个新的端口来承载 Mock Server,相对使用简单,用来做测试还是挺方便的。体验上的不足就是 Network 面板看不到请求了,不过可以接受。
示例:
import { createServer } from "miragejs"createServer({routes() {this.namespace = "api"this.get("/movies", () => {return {movies: [{ id: 1, name: "Inception", year: 2010 },{ id: 2, name: "Interstellar", year: 2014 },{ id: 3, name: "Dunkirk", year: 2017 },],}})},
})
超时配置
this.get("/movies",() => {return {movies: [{ id: 1, name: "Inception", year: 2010 },{ id: 2, name: "Interstellar", year: 2014 },{ id: 3, name: "Dunkirk", year: 2017 },],}},{ timing: 4000 }
)
OR
this.get("/movies", () => {return new Promise((res) => {setTimeout(() => {res({movies: [{ id: 1, name: "Inception", year: 2010 },{ id: 2, name: "Interstellar", year: 2014 },{ id: 3, name: "Dunkirk", year: 2017 },],});}, 4000);});
});
根据 url 参数动态配置超时:
// fetch("/movies?t=2000")
this.get("/movies", (_, req) => {return new Promise((res) => {setTimeout(() => {res({movies: [{ id: 1, name: "Inception", year: 2010 },{ id: 2, name: "Interstellar", year: 2014 },{ id: 3, name: "Dunkirk", year: 2017 },],});}, req.queryParams.t || 0);});
});
请求直通
官方的文档不生效,看了下代码实现有问题,如下:
// createPretender
this.checkPassthrough = function (request) {let shouldPassthrough = server.passthroughChecks.some((passthroughCheck) => passthroughCheck(request));if (shouldPassthrough) {let url = request.url.includes("?")? request.url.substr(0, request.url.indexOf("?")): request.url;this[request.method.toLowerCase()](url, this.passthrough);}return originalCheckPassthrough.apply(this, arguments);
};// Server
passthrough(...paths) {// this only works in browser-like environments for now. in node users will have to configure// their own interceptor if they are using one.if (typeof window !== "undefined") {let verbs = ["get", "post", "put", "delete", "patch", "options", "head"];let lastArg = paths[paths.length - 1];if (paths.length === 0) {paths = ["/**", "/"];} else if (Array.isArray(lastArg)) {verbs = paths.pop();}paths.forEach((path) => {if (typeof path === "function") {this.passthroughChecks.push(path);} else {verbs.forEach((verb) => {let fullPath = this._getFullPath(path);this.pretender[verb](fullPath, this.pretender.passthrough);});}});}
}
可以采用这种方式,来把 namespace
外的请求,都不做处理,把以下代码入到 routes 中执行:
this.passthrough((req) => {return req.url.indexOf(this.namespace) === -1;
});