All Projects → solufa → axios-mock-server

solufa / axios-mock-server

Licence: MIT license
RESTful mock server using axios.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Labels

Projects that are alternatives of or similar to axios-mock-server

Vue Admin Webapp
this is a admin project
Stars: ✭ 673 (+1939.39%)
Mutual labels:  mock, axios
React Nativeish
React Native / React Native Web Boilerplate
Stars: ✭ 106 (+221.21%)
Mutual labels:  mock, axios
Vue3 Admin
👏vue3.0后台管理框架👏基于vue-cli4+compositionAPI+vue-router4
Stars: ✭ 54 (+63.64%)
Mutual labels:  mock, axios
admin-antd-vue
Vue3.x + Ant Design Admin template (vite/webpack)
Stars: ✭ 111 (+236.36%)
Mutual labels:  mock, axios
electron-admin-antd-vue
Electron Vue3.x Ant Design Admin template
Stars: ✭ 21 (-36.36%)
Mutual labels:  mock, axios
Dva Admin
dva admin antd dashboard
Stars: ✭ 278 (+742.42%)
Mutual labels:  mock, axios
Vue Lottery
🎨 抽奖以及截屏保存图片至本地
Stars: ✭ 90 (+172.73%)
Mutual labels:  mock, axios
h-blog
vue+elementUI模仿我的博客,简单的写的几个练习页面
Stars: ✭ 14 (-57.58%)
Mutual labels:  mock, axios
Vue Blog
🎉 基于vue全家桶 + element-ui 构建的一个后台管理集成解决方案
Stars: ✭ 208 (+530.3%)
Mutual labels:  mock, axios
Vue Cli Multi Page
基于vue-cli模板的多页面多路由项目,一个PC端页面入口,一个移动端页面入口,且有各自的路由, vue+webpack+vue-router+vuex+mock+axios
Stars: ✭ 145 (+339.39%)
Mutual labels:  mock, axios
vue-admin-better
🚀🚀🚀vue admin,vue3 admin,vue3.0 admin,vue后台管理,vue-admin,vue3.0-admin,admin,vue-admin,vue-element-admin,ant-design,vue-admin-beautiful-pro,vab admin pro,vab admin plus,vue admin plus,vue admin pro
Stars: ✭ 12,962 (+39178.79%)
Mutual labels:  mock, axios
Axios Mock Adapter
Axios adapter that allows to easily mock requests
Stars: ✭ 2,832 (+8481.82%)
Mutual labels:  mock, axios
vue-admin-work
🎉🎉🚀🚀🚀🚀vue-admin-work是一个中后台系统管理方案。使用 vue2.x 及周边全家桶工具开发而来。支持多种功能,不同角色权限🚀🚀🚀🎉🎉
Stars: ✭ 74 (+124.24%)
Mutual labels:  mock, axios
Vue Cms
基于 Vue 和 ElementUI 构建的一个企业级后台管理系统
Stars: ✭ 415 (+1157.58%)
Mutual labels:  mock, axios
electron-admin-element-vue
Electron Vue3.x Element-UI Admin
Stars: ✭ 37 (+12.12%)
Mutual labels:  mock, axios
Vue Admin Beautiful
🚀🚀🚀vue3 admin,vue3.0 admin,vue后台管理,vue-admin,vue3.0-admin,admin,vue-admin,vue-element-admin,ant-design,vue-admin-beautiful-pro,vab admin pro,vab admin plus主线版本基于element-plus、element-ui、ant-design-vue三者并行开发维护,同时支持电脑,手机,平板,切换分支查看不同的vue版本,element-plus版本已发布(vue3,vue3.0,vue,vue3.x,vue.js)
Stars: ✭ 10,968 (+33136.36%)
Mutual labels:  mock, axios
wwvue-cli
vue-cli升级版脚手架,应有尽有的开箱即用方法及配置,没有花里胡哨的晦涩难懂的操作,上手成本极低,现已新增simple(极简模式)、vue3和iview-template,是个很不错的垫脚石,来不及解释了赶紧上车😊😘
Stars: ✭ 15 (-54.55%)
Mutual labels:  mock, axios
chrome-extension-mocker
The most convenient tool to mock requests for axios, with built-in Chrome extension support.
Stars: ✭ 37 (+12.12%)
Mutual labels:  mock, axios
D2 Admin
An elegant dashboard
Stars: ✭ 11,012 (+33269.7%)
Mutual labels:  mock, axios
Nx Admin
👍 A magical 🐮 ⚔ vue admin,记得star
Stars: ✭ 2,497 (+7466.67%)
Mutual labels:  mock, axios

🇺🇸English | 🇯🇵日本語

axios-mock-server

npm version npm bundle size CircleCI Codecov Language grade: JavaScript Dependabot Status License

RESTful mock server using axios.

Table of contents

Features

  • You can create a GET/POST/PUT/DELETE API endpoint in a few lines.
  • A dedicated server is not required.
  • It works with SPA as a static JavaScript file.
  • You can use axios as mock-up even in Node.js environment.
  • There is an auto-routing function similar to Nuxt.js, and no path description is required.
  • Supports TypeScript.

Getting Started

Installation

  • Using npm:

    $ npm install axios
    $ npm install axios-mock-server --save-dev
  • Using Yarn:

    $ yarn add axios
    $ yarn add axios-mock-server --dev

Tutorial

Introducing the simplest use of axios-mock-server.

Start the tutorial

Create API

First, create a mocks directory to store the files you want to mock up.

$ mkdir mocks

Next, create an API endpoint file in the mocks directory.
Let's define a mock API that retrieves basic user information with a GET request.

Create a mocks/users directory and create a _userId.js file.

$ mkdir mocks/users
$ touch mocks/users/_userId.js

# If Windows (Command Prompt)
> mkdir mocks\users
> echo. > mocks\users\_userId.js

Add the following to the mocks/users/_userId.js file.

// file: 'mocks/users/_userId.js'
const users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }]

module.exports = {
  get({ values }) {
    return [200, users.find(user => user.id === values.userId)]
  }
}

The routing of axios-mock-server is automatically generated according to the tree structure of JavaScript and TypeScript files in the mocks directory in the same way as the routing of Nuxt.js.

Reference: Routing - Nuxt.js

In other words, the mocks/users/_userId.js file can define an endpoint using dynamic routing as the path of /users/:userId.

Build API

axios-mock-server needs to build and generate the necessary files for routing before running.

$ node_modules/.bin/axios-mock-server

# If Windows (Command Prompt)
> node_modules\.bin\axios-mock-server

If the build is successful, the $mock.js file is generated in themocks directory.

$ cat mocks/\$mock.js
/* eslint-disable */
module.exports = (client) => require('axios-mock-server')([
  {
    path: '/users/_userId',
    methods: require('./users/_userId')
  }
], client)

# If Windows (Command Prompt)
> type mocks\$mock.js

Mocking Axios

Finally, import the mocks/$mock.js file generated by index.js file etc. and pass it to the argument of axios-mock-server.
axios-mock-server will mock up all axios communications by default.

// file: 'index.js'
const axios = require('axios')
const mock = require('./mocks/$mock.js')

mock()

axios.get('https://example.com/users/1').then(({ data }) => {
  console.log(data)
})

If you run the index.js file, you will see that { id: 1, name: 'bar' } is returned.

$ node index.js
{ id: 1, name: 'bar' }

Examples

axios-mock-server can be used to mock up browser usage, data persistence and multipart/form-data format communication.
It is also easy to link with Nuxt.js (@nuxtjs/axios).

See examples for source code.

See a list of use cases

WIP

  • with-in-memory-database

Usage

Create an API endpoint

const users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }]

/**
 * Type definitions for variables passed as arguments in requests
 * @typedef { Object } MockMethodParams
 * @property { import('axios').AxiosRequestConfig } config axios request settings
 * @property {{ [key: string]: string | number }} values Dynamic value of the requested URL (underscore part of the path)
 * @property {{ [key: string]: any }} params The value of the query parameter for the requested URL
 * @property { any } data Request data sent by POST etc.
 */

/**
 * Type definition when response is returned as an object
 * @typedef { Object } MockResponseObject
 * @property { number } status HTTP response status code
 * @property { any? } data Response data
 * @property {{ [key: string]: any }?} headers Response header
 */

/**
 * Response type definition
 * @typedef { [number, any?, { [key: string]: any }?] | MockResponseObject } MockResponse
 */

export default {
  /**
   * All methods such as GET and POST have the same type
   * @param { MockMethodParams }
   * @returns { MockResponse }
   */
  get({ values }) {
    return [200, users.find(user => user.id === values.userId)]
  },

  /**
   * You can also return a response asynchronously
   * @param { MockMethodParams }
   * @returns { Promise<MockResponse> }
   */
  async post({ data }) {
    await new Promise(resolve => setTimeout(resolve, 1000))

    users.push({
      id: users.length,
      name: data.name
    })

    return { status: 201 }
  }
}

Connect to axios

Default

axios-mock-server will mock up all axios communications by default.

import axios from 'axios'
import mock from './mocks/$mock.js'

mock()

axios.get('https://example.com/api/foo').then(response => {
  /* ... */
})

Each instance

You can also mock up each axios instance.

import axios from 'axios'
import mock from './mocks/$mock.js'

const client = axios.create({ baseURL: 'https://example.com/api' })

mock(client)

client.get('/foo').then(response => {
  /* ... */
})

// axios will not be mocked up
axios.get('https://example.com/api/foo').catch(error => {
  console.log(error.response.status) // 404
})

Functions

axios-mock-server has several built-in functions available.

setDelayTime(millisecond: number): void

Simulate response delay.

import axios from 'axios'
import mock from './mocks/$mock.js'

mock().setDelayTime(500)

console.time()
axios.get('https://example.com/api/foo').then(() => {
  console.timeEnd() // default: 506.590ms
})

enableLog(): void and disableLog(): void

Switch request log output.

import axios from 'axios'
import mock from './mocks/$mock.js'

const mockServer = mock()

;(async () => {
  // To enable
  mockServer.enableLog()
  await axios.get('/foo', { baseURL: 'https://example.com/api', params: { bar: 'baz' } }) // stdout -> [mock] get: /foo?bar=baz => 200

  // To disable
  mockServer.disableLog()
  await axios.get('/foo', { baseURL: 'https://example.com/api', params: { bar: 'baz' } }) // stdout ->
})()

TypeScript

axios-mock-server includes TypeScript definitions.

Cautions

.gitignore

Exclude $mock.js or $mock.ts generated by axios-mock-server in the build from Git monitoring.

$ echo "\$mock.*" >> .gitignore

# If Windows (Command Prompt)
> echo $mock.* >> .gitignore

@ts-ignore, eslint-disable

For TypeScript projects, add a // @ ts-ignore comment to the above line that imports$ mock.ts. If @typescript-eslint/ban-ts-ignore rule is enabled in typescript-eslint, please exclude the // @ ts-ignore comment from ESLint.

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore: Cannot find module
import mock from './mocks/$mock'

Troubleshooting

The expected type comes from property 'get' which is declared here on type 'MockMethods' error in TypeScript

When returning a response asynchronously with TypeScript, an error occurs because the type does not match if you try to make the response an array.
Assert MockResponse or return it as an object.

Example of error (Note that the axios-mock-server build will pass!)

import { MockMethods } from 'axios-mock-server'

const methods: MockMethods = {
  async get() {
    await new Promise(resolve => setTimeout(resolve, 100))
    return [200, { foo: 'bar' }] // Error
  }
}

export default methods

Resolve by asserting MockResponse.

import { MockMethods, MockResponse } from 'axios-mock-server'

const methods: MockMethods = {
  async get() {
    await new Promise(resolve => setTimeout(resolve, 100))
    return [200, { foo: 'bar' }] as MockResponse // Type safe
  }
}

export default methods

If the response can be an object, no assertion is required.

import { MockMethods } from 'axios-mock-server'

const methods: MockMethods = {
  async get() {
    await new Promise(resolve => setTimeout(resolve, 100))
    return { status: 200, data: { foo: 'bar' } } // Type safe
  }
}

export default methods

Command Line Interface Options

The following options can be specified in the Command Line Interface.

Option Type Default Description
--config
-c
string ".mockserverrc" Specify the path to the configuration file.
--watch
-w
Enable watch mode.
Regenerate $mock.js or $mock.ts according to the increase / decrease of the API endpoint file.
--version
-v
Print axios-mock-server version.

Configuration

Settings are written in .mockserverrc file with JSON syntax.

Option Type Default Description
input string | string[] "mocks" or "apis" Specify the directory where the API endpoint file is stored.
If multiple directories are specified, $mock.js or $mock.ts is generated in each directory.
outputExt "js" | "ts" Specify the extension of the file to be generated.
The default is set automatically from scripts of the API endpoint file.
outputFilename string "$mock.js" or "$mock.ts" Specify the filename to be generated.
target "es6" | "cjs" Specify the code of the module to be generated.
The default is set automatically from extension of the API endpoint file.

License

axios-mock-server is licensed under a MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].