注:本文是《前端Mock选型大全》的模块。
0 按
我记得有人在慕课网分享过msw,说是有了它就不需要提供后端服务了,我今天试了试的确好用。
充分利用 serviceWorker 可以拦截请求并进行缓存的原理,拿来做mock很方便。
1 技术卡片
| 新技术QA | |
|---|---|
| 技术名称 | mock-service-worker, msw |
| 文档官网 | https://mswjs.io 需科学上网 |
| 作者、技术团队 | |
| 能做解决什么问题 | mock数据繁琐 |
| 特点、优点 | 基于sw,思路清奇,操作简单 |
| 同类选型 | mockjs,nock,json server,service mocker |
| 缺点、踩坑注意 | |
| 宣传语 | API mocking of the next generation 下一代的api mock |
| 选型关键词 | mock |
官网介绍语:
API mocking of the next generation 下一代的api mock
Mock by intercepting requests on the network level. Seamlessly reuse the same mock definition for testing, development, and debugging. 在网络层面拦截并模拟。项目开发轻松复用mock定义。
基础使用
注意:本次教程针对 浏览器+vue.js,不考虑 node环境。
安装依赖、创建sw文件
yarn add -D msw# 生成一个sw文件,并存入 package.jsonnpx msw init public/ --save
- 这一步init的操作是生成一段sw脚本
- 设定存放的路径为
public,避免参与编译,后续worker.start默认使用 https://mswjs.io/docs/api/setup-worker/start#options - 设定
--save在package.json中添加nsw.workDirectory,方便msw后续更新补充功能或者修bug,而且
准备mock
总体流程:
- 引入依赖
- 定义请求方法、路径、响应体
- 功能启动
可以把这段代码放入 src/main.js 中:
import { setupWorker, rest } from 'msw'const worker = setupWorker([rest.get('/api/x',(req,res,ctx) => {return res(ctx.json({a:1}))})])// worker.start() // 核心是这个,更推荐通过环境变量来控制if (import.meta.env.DEV) {worker.start();} else {console.log("prod");}
页面里去请求,不区分 xhr/fetch ,就能拿到结果了。

-1 参考资料
官网提供了一个更完整的案例可参考:
// src/mocks/handlers.jsimport { rest } from 'msw'export const handlers = [rest.post('/login', (req, res, ctx) => {// Persist user's authentication in the sessionsessionStorage.setItem('is-authenticated', 'true')return res(// Respond with a 200 status codectx.status(200),)}),rest.get('/user', (req, res, ctx) => {// Check if the user is authenticated in this sessionconst isAuthenticated = sessionStorage.getItem('is-authenticated')if (!isAuthenticated) {// If not authenticated, respond with a 403 errorreturn res(ctx.status(403),ctx.json({errorMessage: 'Not authorized',}),)}// If authenticated, return a mocked user detailsreturn res(ctx.status(200),ctx.json({username: 'admin',}),)}),]
