Installations
npm install sb-axios-mock-server
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
12.16.1
NPM Version
6.13.4
Score
71.8
Supply Chain
98.9
Quality
74.6
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (96.8%)
JavaScript (3.2%)
Developer
Download Statistics
Total Downloads
2,240
Last Day
2
Last Week
5
Last Month
18
Last Year
226
GitHub Statistics
34 Stars
627 Commits
5 Forks
1 Watching
22 Branches
3 Contributors
Bundle Size
14.67 kB
Minified
4.10 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.18.2
Package Id
sb-axios-mock-server@0.18.2
Unpacked Size
93.86 kB
Size
24.33 kB
File Count
85
NPM Version
6.13.4
Node Version
12.16.1
Total Downloads
Cumulative downloads
Total Downloads
2,240
Last day
0%
2
Compared to previous day
Last week
25%
5
Compared to previous week
Last month
200%
18
Compared to previous month
Last year
-71.8%
226
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
3
Dev Dependencies
19
🇺🇸English | 🇯🇵日本語
axios-mock-server
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.
- small func added by sb
Getting Started
Installation
-
Using npm:
1$ npm install axios 2$ npm install axios-mock-server --save-dev
-
Using Yarn:
1$ yarn add axios 2$ 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.
1$ 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.
1$ mkdir mocks/users 2$ touch mocks/users/_userId.js 3 4# If Windows (Command Prompt) 5> mkdir mocks\users 6> echo. > mocks\users\_userId.js
Add the following to the mocks/users/_userId.js
file.
1// file: 'mocks/users/_userId.js' 2const users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }] 3 4module.exports = { 5 get({ values }) { 6 return [200, users.find(user => user.id === values.userId)] 7 } 8}
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.
1$ node_modules/.bin/axios-mock-server 2 3# If Windows (Command Prompt) 4> node_modules\.bin\axios-mock-server
If the build is successful, the $mock.js
file is generated in themocks
directory.
1$ cat mocks/\$mock.js 2/* eslint-disable */ 3module.exports = (client) => require('axios-mock-server')([ 4 { 5 path: '/users/_userId', 6 methods: require('./users/_userId') 7 } 8], client) 9 10# If Windows (Command Prompt) 11> 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.
1// file: 'index.js' 2const axios = require('axios') 3const mock = require('./mocks/$mock.js') 4 5mock() 6 7axios.get('https://example.com/users/1').then(({ data }) => { 8 console.log(data) 9})
If you run the index.js
file, you will see that { id: 1, name: 'bar' }
is returned.
1$ node index.js 2{ 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
- browser: Use in browser
- node: Use in Node.js (CommonJS)
- with-nuxtjs: Using with a Nuxt.js
- with-typescript: Using with a TypeScript
WIP
- with-in-memory-database
Usage
Create an API endpoint
1const users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }] 2 3/** 4 * Type definitions for variables passed as arguments in requests 5 * @typedef { Object } MockMethodParams 6 * @property { import('axios').AxiosRequestConfig } config axios request settings 7 * @property {{ [key: string]: string | number }} values Dynamic value of the requested URL (underscore part of the path) 8 * @property {{ [key: string]: any }} params The value of the query parameter for the requested URL 9 * @property { any } data Request data sent by POST etc. 10 */ 11 12/** 13 * Type definition when response is returned as an object 14 * @typedef { Object } MockResponseObject 15 * @property { number } status HTTP response status code 16 * @property { any? } data Response data 17 * @property {{ [key: string]: any }?} headers Response header 18 */ 19 20/** 21 * Response type definition 22 * @typedef { [number, any?, { [key: string]: any }?] | MockResponseObject } MockResponse 23 */ 24 25export default { 26 /** 27 * All methods such as GET and POST have the same type 28 * @param { MockMethodParams } 29 * @returns { MockResponse } 30 */ 31 get({ values }) { 32 return [200, users.find(user => user.id === values.userId)] 33 }, 34 35 /** 36 * You can also return a response asynchronously 37 * @param { MockMethodParams } 38 * @returns { Promise<MockResponse> } 39 */ 40 async post({ data }) { 41 await new Promise(resolve => setTimeout(resolve, 1000)) 42 43 users.push({ 44 id: users.length, 45 name: data.name 46 }) 47 48 return { status: 201 } 49 } 50}
Connect to axios
Default
axios-mock-server will mock up all axios communications by default.
1import axios from 'axios' 2import mock from './mocks/$mock.js' 3 4mock() 5 6axios.get('https://example.com/api/foo').then(response => { 7 /* ... */ 8})
Each instance
You can also mock up each axios instance.
1import axios from 'axios' 2import mock from './mocks/$mock.js' 3 4const client = axios.create({ baseURL: 'https://example.com/api' }) 5 6mock(client) 7 8client.get('/foo').then(response => { 9 /* ... */ 10}) 11 12// axios will not be mocked up 13axios.get('https://example.com/api/foo').catch(error => { 14 console.log(error.response.status) // 404 15})
Functions
axios-mock-server has several built-in functions available.
setDelayTime(millisecond: number): void
Simulate response delay.
1import axios from 'axios' 2import mock from './mocks/$mock.js' 3 4mock().setDelayTime(500) 5 6console.time() 7axios.get('https://example.com/api/foo').then(() => { 8 console.timeEnd() // default: 506.590ms 9})
enableLog(): void
and disableLog(): void
Switch request log output.
1import axios from 'axios' 2import mock from './mocks/$mock.js' 3 4const mockServer = mock() 5 6;(async () => { 7 // To enable 8 mockServer.enableLog() 9 await axios.get('/foo', { baseURL: 'https://example.com/api', params: { bar: 'baz' } }) // stdout -> [mock] get: /foo?bar=baz => 200 10 11 // To disable 12 mockServer.disableLog() 13 await axios.get('/foo', { baseURL: 'https://example.com/api', params: { bar: 'baz' } }) // stdout -> 14})()
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.
1$ echo "\$mock.*" >> .gitignore 2 3# If Windows (Command Prompt) 4> 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.
1// eslint-disable-next-line @typescript-eslint/ban-ts-ignore 2// @ts-ignore: Cannot find module 3import 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!)
1import { MockMethods } from 'axios-mock-server' 2 3const methods: MockMethods = { 4 async get() { 5 await new Promise(resolve => setTimeout(resolve, 100)) 6 return [200, { foo: 'bar' }] // Error 7 } 8} 9 10export default methods
Resolve by asserting MockResponse
.
1import { MockMethods, MockResponse } from 'axios-mock-server' 2 3const methods: MockMethods = { 4 async get() { 5 await new Promise(resolve => setTimeout(resolve, 100)) 6 return [200, { foo: 'bar' }] as MockResponse // Type safe 7 } 8} 9 10export default methods
If the response can be an object, no assertion is required.
1import { MockMethods } from 'axios-mock-server' 2 3const methods: MockMethods = { 4 async get() { 5 await new Promise(resolve => setTimeout(resolve, 100)) 6 return { status: 200, data: { foo: 'bar' } } // Type safe 7 } 8} 9 10export 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. | |
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.
![Empty State](/_next/static/media/empty.e5fae2e5.png)
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 0/25 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/nodejs.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:44: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:46: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/nodejs.yml:53: update your workflow using https://app.stepsecurity.io/secureworkflow/solufa/axios-mock-server/nodejs.yml/master?enable=pin
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Reason
37 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-cph5-m8f7-6c5x
- Warn: Project is vulnerable to: GHSA-wf5p-g6vw-rhxx
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-74fj-2j2h-c42q
- Warn: Project is vulnerable to: GHSA-pw2r-vq6v-hr8c
- Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc
- Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp
- Warn: Project is vulnerable to: GHSA-ww39-953v-wcq6
- Warn: Project is vulnerable to: GHSA-765h-qjxv-5f44
- Warn: Project is vulnerable to: GHSA-f2jv-r9rf-7988
- Warn: Project is vulnerable to: GHSA-43f8-2h32-f4cj
- Warn: Project is vulnerable to: GHSA-896r-f27r-55mw
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-4rq4-32rv-6wp6
- Warn: Project is vulnerable to: GHSA-64g7-mvw6-v9qj
- Warn: Project is vulnerable to: GHSA-jgrx-mgxx-jf9v
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-7p7h-4mm5-852v
- Warn: Project is vulnerable to: GHSA-38fc-wpqx-33j7
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-6fc8-4gx4-v693
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-c4w7-xm78-47vh
Score
2.8
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More