Use mocks in your projects
August more text fifth play, start! 🍦
This is the fifth day of my participation in the August challenge. In the development process of our front end, we often encounter that the development is in parallel with the back-end development or the progress is faster than the back-end development. In this case, we have no test data, so we can’t wait for the back-end outbound interface. As an efficient developer, how can we tolerate this? Mock data solves this problem for us. So how do you access mock data in your project
Installing mock dependencies
npm install mockjs
Create a mock directory
Create a mock directory in the root directory, along with the index.js, API, and node directories
index.js
Entry file to import the mock, read the mock data directory, and register to generate the mock interface
/* eslint-disable */ const Mock = require('mockjs'); Import mockPaths from '@/store' const mockPaths = [] Const files = require.context('./ API ', true, /\.ts$/) files.keys().forEach(key => { const file = files(key).default mockPaths.push(... File)}) // Store the mock address store.dispatch('common/ setPath ', mockPaths) any) => { Mock.mock(item.url, item.type, require(`./json${item.path}`)); })Copy the code
Store to create a storage mock interface
namespaced: true,
state: {
mockPath: []
},
mutations: {
MOCKPATH(state: any, val: any) {
state.mockPath = val
}
},
actions: {
setMockPath({ commit }: any, fn: any) {
commit('MOCKPATH', fn)
}
}
}
Copy the code
API directory
The API directory is the same as the real API directory user.js
/* eslint-disable */
export default [
{ name: 'userInfo', type: 'get', url: '/user/userInfo', path: '/user/userInfo' }
]
Copy the code
The node directory level
User -> userinfo.json
{" result ":" success ", "data" : {" userSn ":" 01 ", "username" : "KouKou bacteria", "age" : 25, "imgUrl" : ""}," MSG ":" "}Copy the code
Vue use
Use mock data in a VUE project
Import the mock configuration file
Import files in main.js
// import the mock data and close it to comment the line require('./mock')Copy the code
Mock vs. non-mock request interface judgment in AXIOS
In specific usage scenarios, we will encounter some interfaces to mock, some not to mock, here is to judge the mock interface.
/ * * request interceptor * / axios. Interceptors. Request. Use ((config: Any) = > {/ / change the mock data url const mockPath = store.state.com mon. MockPath mockPath. The map ((item: any) => { if (item.url == config.url) { config.baseURL = '' } }) })Copy the code
Test on the page
You can get the mock data by accessing the page using the currently configured mock URL
handleClick
Tests for independent AxioshandleClickCommon
Tests for global AXIOS
<template> <div> <van-button type="primary" @click="_handleClick"> Mock request </van-button> <hr /> <div> {{resMsg}} </div> <hr /> < span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: normal;" </div> </div> </template> <script> import axios from 'axios' export default { data() { return { resMsg: '', resMsgCommon: '' } }, methods: { _handleClick() { axios .get('/user/userInfo') .then(res => { console.log(res) this.resMsg = res.data }) .catch(err => { console.error(err) }) }, _handleClickCommon() { this.$Request .requestGet({}, this.$api.app.userInfo) .then(res => { console.log(res) this.resMsgCommon = res }) .catch(err => { console.error(err) }) } } } </script>Copy the code
conclusion
The end of this article, hope to help you 😉