Mocks webpack dev server request in an easy configurable way
Install with npm:
npm install --save-dev webpack-mock-dev-server
Install with yarn:
yarn add webpack-mock-dev-server --dev
webpack-mock-dev-server is an easy to configure webpack helper which allows to mock request passing through the webpack-dev-server. In the configuration file you can specify which requests should be mocked and what response you would like to return. It also allows to set specific headers on the response.
TL;DR
- Mock wepack-dev-server responses
- Easy configuration
- Allows to specify headers on the response
Open the webpack configuration file in which you have specified the dev-server configuration.
Modify the configuration like the example (1) below. Most of the time it would be needed to just add
the 'before' configuration option as shown in example 1. If you already have specified a function on the before
configuration option, call the MockDevServer function al shown in example 2.
Example 1:
const { MockDevServer } = require('webpack-mock-dev-server');
module.exports = {
...,
devServer: {
...,
before: MockDevServer(path.join(__dirname, 'mock-dev-server.config')),
}
};
Example 2:
const { MockDevServer } = require('webpack-mock-dev-server');
module.exports = {
...,
devServer: {
...,
before: function before(app, server) {
MockDevServer(path.join(__dirname, 'mock-dev-server.config'))(app);
},
}
};
The only argument needed is the path to the configuration file. If not specified it will look
for the file in the same directory as the webpack config file.
By default this will mock all response and throw warnings on all requests that do not have
a rule specified in the config file. See Configuration to specify responses
for specific requests.
Create a file (mock-dev-server.config.js by default) in which you would like to specify the mocking configurations. See the example below.
module.exports = {
src: path.join(__dirname, 'fixtures'),
entry: '/api/*',
rules: [
{
method: 'GET',
test: '**/news',
filename: 'news.json',
headers: {
'Content-Type': 'application/json'
}
},
],
}
Property list:
- src: the base path to use when requesting mock files (fixtures). So the filename specified in the rules is relative to this path.
- entry: the base path to use when targeting requests in the dev-server. So each test in the rules is relative to this path.
- rules: The set of rules to check when a requests occurs.
- method (optional, default: GET): the method of the request
- test: the glob expression to match against
- filename: the name of the file to return it's content from when the test succeeds.
- headers (optional): any headers that need to be set them mocking the response.