Gathering detailed insights and metrics for axios-mock-server
Gathering detailed insights and metrics for axios-mock-server
npm install axios-mock-server
Typescript
Module System
Node Version
NPM Version
75.1
Supply Chain
99.5
Quality
77.8
Maintenance
100
Vulnerability
100
License
TypeScript (96.8%)
JavaScript (3.2%)
Total Downloads
370,553
Last Day
118
Last Week
693
Last Month
4,202
Last Year
51,445
34 Stars
627 Commits
5 Forks
1 Watching
22 Branches
3 Contributors
Minified
Minified + Gzipped
Latest Version
0.19.1
Package Id
axios-mock-server@0.19.1
Unpacked Size
93.31 kB
Size
24.61 kB
File Count
85
NPM Version
6.14.10
Node Version
12.20.1
Cumulative downloads
Total Downloads
Last day
-16.9%
118
Compared to previous day
Last week
-48.4%
693
Compared to previous week
Last month
66.7%
4,202
Compared to previous month
Last year
-26.2%
51,445
Compared to previous year
3
19
RESTful mock server using axios.
GET
/POST
/PUT
/DELETE
API endpoint in a few lines.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
Introducing the simplest use of axios-mock-server.
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
.
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
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' }
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.
WIP
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}
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})
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})
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})()
axios-mock-server includes TypeScript definitions.
.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'
The expected type comes from property 'get' which is declared here on type 'MockMethods'
error in TypeScriptWhen 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
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. |
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. |
axios-mock-server is licensed under a MIT License.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
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
Reason
Found 0/25 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
37 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-20
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