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);
});
});
请求直通
官方的文档不生效,看了下代码实现有问题,如下:
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);
};
passthrough(...paths) {
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 外的请求,都不做处理:
this.passthrough((req) => {
return req.url.indexOf(this.namespace) !== 0;
});
|