前端 Mock 工具
生活随笔
收集整理的這篇文章主要介紹了
前端 Mock 工具
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
| 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; });總結
以上是生活随笔為你收集整理的前端 Mock 工具的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022年五一建模比赛A题#五一建模
- 下一篇: gulp+PC前端静态页面项目开发