Using Mockjs step analysis in vue-cli project

php中世界最好的语言
Release: 2018-05-21 14:42:54
Original
1878 people have browsed it

This time I will bring you an analysis of the steps for using Mockjs in the vue-cli project. What are theprecautionsfor using Mockjs in the vue-cli project. The following is a practical case, let's take a look.

Background

Front-end In the early jQuery era, front-end functions and back-end engineering were basically combined. The typical one was common The webapp directory under the maven project contains various front-end static resource files.

At this time, we always encounter these problems:

  1. Boss, the interface document has not been output yet, so I can’t do a lot of work!

  2. Backend guy, have you written the interface? I want to test it!

  3. There is not enough time for testing, and the version is about to be released. Did I watch the sun rise tomorrow today?

All kinds of things, just one sentence: Labor and management, don’t count on you anymore!

After node appeared, or to be precise, after the separation of front-end and back-end, the front-end urgently needed a mechanism that no longer needed to rely on back-end interface development. After several years of development, many big names have conducted research in this area.

Now we can finally implement real simulation testing. For example, today’s protagonist mockjs

Usage details

1. First create a mock folder in the src directory and define the mock main file index.js. Define the interception routing configuration in this file;

/** * 定义本地测试接口,最好与正式接口一致,避免联调阶段修改工作量 */ // 引入mockjs import Mock from 'mockjs'; // 引入模板函数类 import record from './presc-record-api'; Mock.setup({ timeout: 800, // 设置延迟响应,模拟向后端请求数据 }); // Mock.mock( url, post/get , 返回的数据); Mock.mock(/\/api\/healthPlat\/getRecipe\/\w*\/\w*/, 'get', record.getRecipe);
Copy after login

2. Define the template function class in the specified file, example:

// 获取 mock.Random 对象 // 引入mockjs import { Random } from 'mockjs'; import Utils from './Utils'; function getRecipe(req) { // mock一组数据 const data = []; for (let i = 0; i < 10; i += 1) { const o = { recipeId: Random.guid(), billId: Random.string(10), orgId: Random.string('number', 8, 10), viewName: Random.cword(4, 16), // 随机生成任意名称 personName: Random.cname(), reason: Random.csentence(10, 32), }; data.push(o); } // 返回响应数据对象 return Utils.setRes(req, { data: { idCard: Random.id(), // 随机 details: data, }, totalCount: 20, }); } export default { getRecipe, };
Copy after login

3. Introduce mock/index.js into main.js File;

// 引入mock文件 import './mock/index'; // mock 方式,正式发布时,注释掉该处即可
Copy after login

The next step is to configure your mock routing and template functions. Have Fun!

pitfalls

Here I will introduce the pitfalls when using Mockjs in vue-cli:

1. The request path contains variables, what should I do?

Coders who have used router know that we often have to deal with routes that contain parameters in the address. At this time, we only need to useregular expressionin Mockjs to match the path. Completed, example:

Copy codeThe code is as follows:

Mock.mock(/\/api\/healthPlat\/getRecipeDetail\/\w*\/\w */, 'get', record.getRecipeDetail);

That is, we only use regular character sets in variables to match our variables.

2. Why don’t I see my request in the network in the console?

When I first started testing, I checked the network and didn’t see the request, which was strange! Just ask yourself a few questions:

  1. Why introduce mockjs related configuration files in main.jsentry file?

  2. Aren’t entry files compiled in webpack and then executed in the browser?

  3. The console did not intercept the request, that means it did not intercept the request sent to the server, right?

With these questions, I read the source code and documentation and found:

  1. In the source code, first check whether the request is defined in Mockjs. There is Then intercept, and then use its mock request object MockXMLHttpRequest to respond, that is, no XHR request is sent at this time;

  2. Otherwise, use the local standard XHR object to make the request. At this time, you can make the request in the console network SeeRequest Information

Therefore, introducing the relevant configuration files of mockjs in the main.js entry file means adding the simulation of Mockjs to the front-end code. method, it will be executed in the browser instead of actually sending a request, but we can print it to the console to view it.

Netizens commented that you can use mockjs in the server. At this time, it is a real request. You can view the request information in the console. I have not practiced the corresponding practice here. If you are interested, you can refer to mock-server:

3. Using template syntax, the returned data contains rules "|rules", causing parsing or value acquisition to fail. What should I do?

刚开始的时候,我按照文档上说的模板语法进行配置,如:

看到属性 code 居然带着规则一起返回了,我说我请求为啥没有解析成功啊,原来 res.code 一直是 undefined ,这是坑啊。
查看源码和可以搜到的网上示例发现:没有使用模板规则的现象,而是使用 mockjs 提供的内置函数来实现,如 .id() .cname() 等等方法。

于是我将mock相关文件中 code 定义改成下面这样:

function setRes(req, options) { window.console.log(req.url); const { code = Random.int(0, 5) >= 1 ? 1 : 0, message, data = {}, totalCount = 100 } = options; const result = { code, message: message || ['失败', '错误', '异常'][Random.integer(0, 2)], data, totalCount, }; window.console.log(result); return result; }
Copy after login

刚开始的时候属性code是这样定义的——'code|1', true, ,后来改成了code = Random.boolean(),发现生成 false 的概览太高了,不适合我们真实的场景。

想到我们只需要增加code为 1 的概率,于是本人使用Random.int(0, 5)随机生成一个整数,当这个整数大于等于1,我们将 code 设置为 1 ,其他情况为 0 。

也就是说从概率上将,成功的概率为 0.8,失败的概率为 0.2,基本符合我们测试要求,哈哈,机智不^<^。

4.模拟异步请求的过程,发现请求好像是瞬间完成,loading效果没生效

刚开始的时候,没有设置延迟响应,每次请求都好像是瞬间完成的,没有一步操作的那种等待感,没有看到loading罩层出现。
自己debug时,loading罩层是有的,于是想到:请求没有被延迟,而是被同步执行了。

想到lodash.debounce 函数有延迟网络请求、稀释事件、延迟执行的效果,于是将模板函数用 debounce 包裹起来,如下:

复制代码代码如下:

Mock.mock('/api/healthPlat/chronicdisease', 'get', debounce(record.chronicdisease, 600));

结果出现有意思的事情:当请求比较频繁,在延迟时间内,本次请求得到的响应数据是上次请求的结果。这显然不是我们希望看到的,而且我们一般是用 debounce 的来稀释请求的,用在请求发送之后显然违背了我们的初衷。

翻阅 mockjs 文档,发现作者已经考虑了这个事情。哎,辛苦忙活了大半天,还是要好好看文档啊。具体如下:

Mock.setup({ timeout: 800, // 设置延迟响应,模拟向后端请求数据 });
Copy after login

5. Mock 无法拦截带参数的 get 请求

刚开始时,发现设置的有些 get 请求总是请求不到 mock 的数据,而有些 get 请求能得到 mock 的数据,post 则不存在这样的问题。非常郁闷!

仔细 debug 时发现:get 请求带参数时失败,找不到路径;get 请求不带参数成功,路径没找到,获取到 mock 的数据;post 路径正确找到,成功得到 mock 数据。

这时突然意思到:get 请求的路径默认后面会加上参数,因此和设置的路径没有匹配上,导致路径没找到,请求失败。
于是本人将路径改成正则表达式,就好了。如:

// 刚开始字符串路径,带参数的 get 请求匹配失败 Mock.mock('/api/healthPlat/renewCancel', 'get', manage.renewCancel);
Copy after login

改成下面这样就好了:

// 正则表达式路径,带参数的 get 请求匹配成功 Mock.mock(/\/api\/healthPlat\/renewCancel/, 'get', manage.renewCancel);
Copy after login

但是实际开发过程中,发现上述正则表达式不够完备,如后续我们又另一个路径 /api/healthPlat/renewCancelAddr 也会匹配上述地址,这不是我们希望有的。

此时我们只需改进下正则表达式即可:

// 正则表达式路径,带参数的 get 请求匹配成功 Mock.mock(/\/api\/healthPlat\/renewCancel(|\?\S*)$/, 'get', manage.renewCancel);
Copy after login

即只有路径为 /api/healthPlat/renewCancel 的 get 请求才会匹配上述规则。

最后建议:get 请求都用正则表达式书写路径;post 字符串和正则都行;

总结

mock虽然存在以上所涉及的局限和问题,不过对于日常自测联调还是很有益处,个人觉得主要还是简单可行。当然本文所述方式,不仅仅局限在 vue-cli 中,其他框架中亦可按此法进行配置。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Detailed explanation of the steps to build a react development environment with webpack

Analysis of the steps for using scoped in Vue

The above is the detailed content of Using Mockjs step analysis in vue-cli project. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!