Gathering detailed insights and metrics for http-request-mock
Gathering detailed insights and metrics for http-request-mock
Gathering detailed insights and metrics for http-request-mock
Gathering detailed insights and metrics for http-request-mock
clientlinker
Linker all clients whether rpc, addon, http request, mock data, local file ...
clientlinker-core
Linker all clients whether rpc, addon, http request, mock data, local file ...
@mswjs/interceptors
Low-level HTTP/HTTPS/XHR/fetch request interception library.
fetch-mock
Mock http requests made using fetch
Intercept & mock http requests issued by XMLHttpRequest, fetch, nodejs https/http module, axios, jquery, superagent, ky, node-fetch, request, got or any other request libraries by intercepting XMLHttpRequest, fetch and nodejs native requests at low level.
npm install http-request-mock
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
70 Stars
314 Commits
7 Forks
2 Watching
1 Branches
4 Contributors
Updated on 18 Nov 2024
JavaScript (62.27%)
TypeScript (37.73%)
Cumulative downloads
Total Downloads
Last day
-8.9%
5,705
Compared to previous day
Last week
13.3%
33,779
Compared to previous week
Last month
43.3%
128,851
Compared to previous month
Last year
101.7%
1,152,418
Compared to previous year
41
English | 中文
Full documentation: https://huturen.github.io/http-request-mock-docs/
A quick demo: https://huturen.github.io/http-request-mock-docs/plain-html/
A CURD demo: https://huturen.github.io/http-request-mock-curd/
It mocks http requests issued by axios, jquery, superagent, node-fetch, got, (… you name it) by intercepting XMLHttpRequest, fetch, and nodejs native HTTP/HTTPS module requests at the low level.
Because of the low-level interception, any 3th-party request libraries that based on the above requests can also be supported, such as:
axios
, jquery
, superagent
, ky
, node-fetch
, got
, request
...
It differs from the other mocking libraries in that it provides a webpack plugin and command line tool to separate mock data from your business code. It's a truly non-hacking mocking library. You never have to hack into your business code to mock something ever again after a one-time configuration.
A simple integration case with vue3:
Get the source code of the above case. More integration cases.
http-request-mock
is an http request mocking library that lets you develop, build and test as normal even when
backend APIs are down or not ready yet. It supplies a new way to prototype your web application.
The original intention of making this library was to find a mocking library to decouple from backend. However, we can't find a library that meets our requirements. Some libraries have occupied the most readable names, but they provide weak functionalities or even no longer provide any updates .
There are some problems you may encounter when using the other mocking libraries:
XMLHttpRequest
, some library only for fetch
.NPM:
npm install --save-dev http-request-mock
1// using ES6 modules 2import HttpRequestMock from 'http-request-mock'; 3 4// using CommonJS modules 5const HttpRequestMock = require('http-request-mock');
CDN:
The UMD build is also available on unpkg
:
1<!-- unpkg --> 2<script src="https://unpkg.com/http-request-mock/http-request-mock.js"></script>
You can find the library on window.HttpRequestMock.
To mock an http request, just call a mock
method or http verb method(get
,post
,put
,patch
,delete
).
1import HttpRequestMock from 'http-request-mock'; 2const mocker = HttpRequestMock.setup(); 3 4mocker.mock({ 5 url: 'www.api.com/some-api' // or RegExp: /.*\/some-api$/ 6 method: 'get', // get, post, put, patch or delete 7 delay: 0, 8 status: 200, 9 headers: { // respone headers 10 'content-type': 'application/json', 11 'some-header': 'value', 12 }, 13 body: 'some response data' 14}); 15 16// or using http verb method: 17mocker.get('www.api.com/some-api', 'some response data');
1// mock configuration: 2import HttpRequestMock from 'http-request-mock'; 3const mocker = HttpRequestMock.setup(); 4 5mocker.get('https://www.api.com/text-response', '<html>mock response content</html>'); 6mocker.post('https://www.api.com/json-response', { ret: 0, msg: 'ok' }); 7 8// issue some requests: 9... 10const text = await axios.get('https://www.api.com/text-response'); 11const json = await axios.post('https://www.api.com/json-response', null, { responseType: 'json' }); 12console.log(text); // <html>mock response content</html> 13console.log(json); // { ret: 0, msg: 'ok' } 14...
You can export a function instead of an object to resolve a dynamic response, so as to simulate a complex business logic in the real world.
1// mock configuration: 2import HttpRequestMock from 'http-request-mock'; 3const mocker = HttpRequestMock.setup(); 4 5let times = 0; 6// requestInfo: please refer to < RequestInfo > in src/types.ts 7mocker.get('https://www.api.com/dynamic-response', (requestInfo) => { 8 times = times + 1; 9 return { times: 'times: ' + times, url: requestInfo.url }; 10}); 11 12// Note: the contents of url and times fields are different between the two requests below: 13... 14const res1 = await axios({ url: 'https://www.api.com/dynamic-response?a=1', responseType: 'json' }); 15const res2 = await axios({ url: 'https://www.api.com/dynamic-response?b=2', responseType: 'json' }); 16console.log(res1); // { times: 'times: 1', url: 'https://www.api.com/dynamic-response?a=1' } 17console.log(res2); // { times: 'times: 2', url: 'https://www.api.com/dynamic-response?b=2' } 18...
1// configuration 2import HttpRequestMock from 'http-request-mock'; 3const mocker = HttpRequestMock.setup(); 4mocker.mock({ 5 url: 'https://some.api.com/name', 6 method: 'get', 7 delay: 3000 // the response will be resolved in 3 seconds 8}); 9 10// issue a request: 11let time = Date.now(); 12axios.get('https://some.api.com/name').then(() => { 13 console.log(Date.now() - time); // >= 3000 14});
1// configuration 2import HttpRequestMock from 'http-request-mock'; 3const mocker = HttpRequestMock.setup(); 4mocker.mock({ 5 url: 'www.api.com/status404', 6 status: 404, 7 headers: { 8 'content-type': 'application/json', 9 'some-header': 'header-value', 10 } 11}); 12 13// issue a request: 14// Note: axios will throw an error when meets a 404 response 15axios.get('https://www.api.com/status404').catch(err => { 16 console.log(err.message); // Request failed with status code 404 17 console.log(err.response.status); // 404 18 console.log(err.response.headers['some-header']); // header-value 19});
For more details, please refer to experiment/disable.js
.
1// configuration 2const mocker = HttpRequestMock.setup(); 3const mockItem = mocker.mock({ 4 url: 'https://jsonplaceholder.typicode.com/todos/1', 5 method: 'any', 6 body: {mock: 'some response data'} 7}); 8 9(async () => { 10 const res1 = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); 11 console.log('res1:', res1.data); // it'll resolve a response from mocking. 12 13 mockItem.disable = 'yes'; 14 15 const res2 = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); 16 console.log('res2:', res2.data); // it'll resolve a response from real network request. 17})(); 18 19// res1: { mock: 'some response data' } 20// res2: { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
For more details, please refer to experiment/times.js
:
1const mocker = HttpRequestMock.setup(); 2mocker.mock({ 3 url: 'https://jsonplaceholder.typicode.com/todos/1', 4 method: 'any', 5 times: 2, 6 body: {mock: 'some response data'} 7}); 8 9(async () => { 10 let i = 0; 11 await axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => { 12 console.log(++i, 'res:', res.data); 13 }); 14 await axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => { 15 console.log(++i, 'res:', res.data); 16 }); 17 await axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => { 18 console.log(++i, 'res:', res.data); 19 }); 20})(); 21 22// 1 res: { mock: 'some response data' } 23// 2 res: { mock: 'some response data' } 24// 3 res: { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
1mocker.mock({ 2 url: 'https://www.api.com/reqinfo', 3 response(requestInfo) { 4 return requestInfo; 5 } 6}); 7 8axios.post('https://www.api.com/reqinfo?abc=123', {xyz: 456}, {responseType: 'json'}).then(res => { 9 console.log('info:', res.data); 10}); 11 12// output may look like below: 13// info: { 14// "url": "https://www.api.com/reqinfo?abc=123", 15// "method": "POST", 16// "query": { 17// "abc": "123" 18// }, 19// "headers": { 20// "Accept": "application/json, text/plain, */*", 21// "Content-Type": "application/json;charset=utf-8" 22// }, 23// "body": { 24// "xyz": 456 25// } 26// }
You can intercept a request, do something, then make the original call and capture the response and do something again. For more detailed discussions about the interceptor, please refer to this issue.
1// mock case 2mocker.mock({ 3 url: '//jsonplaceholder.typicode.com/', 4 response: async function(requestInfo) { 5 // 1. intercept a request, do something (here, output the original request information) 6 console.log('original request info: ', requestInfo); 7 8 // 2. then make the original call and capture the response 9 const res = await requestInfo.doOriginalCall(); 10 11 // 3. and do something again. 12 console.log('original response:', res); 13 return { code: 0, msg: 'ok', data: res.responseJson }; 14 } 15}); 16 17// issue a request 18axios.get('https://jsonplaceholder.typicode.com/photos/1').then(res => console.log(res.data));
In a bare-bones example, you just import http-request-mock
into your application
entry file(such as: src/main.js) and configure your mock datas there.
Take a Vue project as an example:
1import { createApp } from 'vue' 2import App from './App.vue' 3import HttpRequestMock from 'http-request-mock' 4 5if (process.env.NODE_ENV === 'development') { 6 const mocker = HttpRequestMock.setup() 7 mocker.get('https://some.api.com/some-path', ...) 8 mocker.post('https://some.api.com/other-path', ...) 9 ... 10} 11 12createApp(App).mount('#app')
It may be ok in a small project, however, for a large web application, it may have lots of APIs to be mocked. You may need frequently change the entry file when adding/deleting/updating a mock data. There will be a day that you'll get a mess as the project grows.
In order to solve the problem above, we provide a webpack plugin and command tool to integrate your project. In this way, the mock data file can be separated from the entry to reduce the burden of managing this entry file.
You can set it up by the steps below:
npx http-request-mock-cli -i
. It'll initialize some samples in your mock directory.HttpRequestMockWebpackPlugin
in your webpack configurations, which looks like below.1const path = require('path'); 2// The webpack plugin will parse mock files under the mock directory and generate a mock 3// configuration entry file named `.runtime.js`, then inject it into the your application entry file. 4const HttpRequestMockWebpackPlugin = require('http-request-mock/plugin/webpack.js'); 5module.exports = { 6 // ... 7 plugins: [ 8 new HttpRequestMockWebpackPlugin( 9 enable: process.env.NODE_ENV === 'development', // activate/deactivate 10 entry: /src\/main\.js$/, // web application entry 11 dir: path.resolve(__dirname, 'mock/'), // mock directory 12 ), 13 ] 14 // ... 15};
mock-dev
to start a mock development:1 "scripts": { 2 "dev": "npm run start", 3 "mock-dev": "NODE_ENV=development npm run start" 4 },
Webpack Plugin options
Option | Required | Description |
---|---|---|
entry | yes | Application entry file, must be a Regexp object |
dir | yes | Mock directory |
enable | no | Whether or not to enable this plugin, default: true |
watch | no | A callback that is triggered when a mock data file is changed |
proxyMode | no | Proxy mode. Valid values: marked |
An alternative way to integrate with your project is using CLI. You can set it up by the steps below:
npx http-request-mock-cli -j src/xxx.js
to inject mock configuration file
into the specified entry which may look like below:1import '../mock/.runtime.js' 2import { createApp } from 'vue' 3import App from './App.vue' 4// ... 5createApp(App).mount('#app')
mock-dev
to start a mock development:1"scripts": { 2 "serve": "vue-cli-service serve", 3 "mock-dev": "http-request-mock-cli -w \"vue-cli-service serve\"", 4},
The command passed into http-request-mock-cli -w
must be quoted with double quotes.
Note:
If -e --environment
is not specified, mock function will be enabled by NODE_ENV=development
.
Or, you can specify another environment variable, such as: -e MOCK=yes
.
npx http-request-mock-cli -h
:
Usage: npx http-request-mock-cli [options]
Description: http-request-mock command line tool at version 1.6.8.
Glossary: [.runtime.js] A runtime mock configuration entry file.
Example:
npx http-request-mock-cli -i
Options:
-d, --directory [directory] The mock directory relative to the working directory. (default: "mock")
-e, --environment [variable-pair] Enable mock function by environment variable for .runtime.js.
(default: "NODE_ENV=development")
-i, --init Initialize some samples & a .runtime.js in the mock directory.
-w, --watch [command] Watch mock directory & update .runtime.js. If the [command] is specified,
ths specified command will be executed together with watching.
-j, --inject <app-entry-file> Inject .runtime.js into the specified entry relative to the working directory.
-t, --type [module-type] The module type of .runtime.js.
Possible values are: es6(alias of ESM), cjs(alias of commonjs).
(default: "cjs")
--index [index-entry] Index entry, automatic detection by default.
Possible values are: src/index.js, http-request-mock.js and http-request-mock.esm.mjs.
[src/index.js] for commonJS
[http-request-mock.js] for UMD
[http-request-mock.pure.js] An alternative version without faker and cache plugins for UMD.
[http-request-mock.esm.mjs] for ESM
[http-request-mock.pure.esm.mjs] An alternative version without faker and cache plugins for ESM.
-p, --proxy [mode] Proxy mode. In proxy mode, http-request-mock will start
a proxy server which receives incoming requests on localhost.
The mock files will be run in a nodejs environment.
This feature is designed for browser, so do not use it in a nodjs project.
Note: proxy mode is still under experimental stage, only for experts.
[matched] All requests matched by @url will be proxied to a proxy server. (default: "none")
-h, --help output usage information
setup() : Mocker:
Auto detect request environment and set up request mock.
setupForWx() : Mocker:
Set up request mock for wx.request.
setupForXhr() : Mocker:
Set up request mock for XMLHttpRequest.
setupForFetch() : Mocker:
Set up request mock for fetch.
setupForNode() : Mocker:
Set up request mock for http.get, https.get, http.request and https.request in nodejs envrioment.
setupForUnitTest() : Mocker:
Set up request mock for unit test.
enable() : Mocker:
Enable mock function temporarily.
disable() : Mocker:
Disable mock function temporarily.
setMockData(mockConfigData: MockConfigData)
Set global mock data configuration.
reset()
Reset global mock data configuration.
mock(mockItem: MockItemInfo)
Check specified mock item & add it to global mock data configuration.
1interface MockItemInfo { 2 url: RegExp | string; 3 method?: HttpVerb; // GET, POST, PUT, PATCH, DELETE or HEAD 4 headers?: Header, // response headers 5 delay?: number; 6 disable?: Disable; // yes or no 7 times?: number; 8 body?: any; // response body 9 status?: number; // http status code 10};
get(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP GET request.
1interface MockItemExt { 2 headers?: Header, // response headers 3 disable?: Disable; // yes or no 4 delay?: number; 5 times?: number; 6 status?: number; // http status code 7};
post(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP POST request.
put(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP PUT request.
patch(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP PATCH request.
delete(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP DELETE request.
head(url: RegExp | String, opts: MockItemExt)
Make a mock item that matches an HTTP HEAD request.
any(url: RegExp | String, body: any, opts: MockItemExt)
Make a mock item that matches an HTTP GET, POST, PUT, PATCH, DELETE or HEAD request.
http-request-mock comes with built-in unit test capability and can be used in jest and mocha environments.
An example of jest:
1import axios from 'axios'; 2import xhrAdapter from 'axios/lib/adapters/xhr'; 3import HttpRequestMock from 'http-request-mock'; 4 5axios.defaults.adapter = xhrAdapter; 6const mocker = HttpRequestMock.setupForUnitTest('xhr'); 7 8mocker.get('https://your.api.com/path', function() { 9 return { abc: 123 }; 10}); 11 12it('should match object`', async () => { 13 const res = await axios.get('https://your.api.com/path'); 14 expect(res.data).toMatchObject({abc: 123}); 15});
1/** 2 * Note: Only the first comments block will be parsed. 3 * 4 * The url to be mocked. 5 * Both string and RegExp(which begins and ends with # or /) are supported. 6 * RegExp example: #.*\/getUserInfo.*# 7 * @url https://jsonplaceholder.typicode.com/todos/1 8 * 9 * The request method to be mocked. 10 * One of http verb method get, post, put, patch, delete, head. 11 * Default: any 12 * @method any 13 * 14 * Response http status to be mocked. 15 * Default: 200 16 * @status 200 17 * 18 * Response http headers to be mocked. 19 * It can be set repeatedly. 20 * @headers content-type: application/json 21 * 22 * Request headers, request headers, only available for @remote tag 23 * It can be set repeatedly. 24 * @remoteRequestHeaders content-type: application/json 25 * 26 * Simulate network latency in milliseconds. 27 * Default: 0 28 * @delay 100 29 * 30 * Limited number of mocking. 31 * It'll do a real network request after specified number of mocking. 32 * Default: Infinity 33 * @times 5 34 * 35 * Whether or not to enable this mock item. 36 * 'yes' for real network request, 'no' for mock request. 37 * Default: no 38 * @disable no 39 * 40 * Remote mock data. 41 * In browser, the specified remote url must conform to the cross-domain specification. 42 * @remote https://remote.api.com/some/mock/data 43 */ 44// Response body to be mocked. 45// It supports to export an object, function, async function, sting or any other types. 46// If a function is specified, the function accepts an argument with request information. 47module.exports = (requestInfo) => { 48 return 'Your response data'; 49};
1. Cannot assign to read only property 'exports' of object '#
No vulnerabilities found.
No security vulnerabilities found.