
Installation
|
Usage
|
Supported Methods
|
Credits
|
License
superagent-mock
superagent plugin allowing to simulate HTTP calls by returning data fixtures based on the requested URL.
See this post to know why we use superagent-mock at Bedrock Streaming.
Installation
Install with npm: npm install superagent-mock
Install with yarn: yarn add superagent-mock
Requirements
node >= 8.0
superagent >= ^3.6.0
Usage
First, you have to define the URLs to mock in a configuration file:
module.exports = [
{
pattern: 'https://domain.example(.*)',
fixtures: function (match, params, headers, context) {
if (match[1] === '/404') {
throw new Error(404);
}
if (match[1] === '/hero') {
if(params['superhero']) {
return 'Your hero:' + params['superhero'];
} else {
return 'You didnt choose a hero';
}
}
if (match[1] === '/authorized_endpoint') {
if(headers['Authorization']) {
return 'Authenticated!';
} else {
throw new Error(401);
}
}
if (match[1] === '/server_test') {
context.cancel = true;
return null;
}
if (match[1] === '/delay_test') {
context.delay = 3000;
return 'zzZ';
}
if (match[1] === '/progress_test') {
context.progress = {
parts: 3,
delay: 1000,
total: 100,
lengthComputable: true,
direction: 'upload'
};
return 'Hundred percent!';
}
},
get: function (match, data) {
return {
body: data
};
},
post: function (match, data) {
return {
status: 201
};
}
},
...
];
Then use the plugin:
var request = require('superagent');
var config = require('./superagent-mock-config');
var superagentMock = require('superagent-mock')(request, config);
...
superagentMock.unset();
Supported methods
All request methods are supported (get, put, post, etc.).
Each request method mock have to be declared in the config file. Otherwise, the callback
method is used.
Logging
You can monitor each call, that has been intercepted by superagent-mock or not, by passing a callback function at initialization.
var request = require('superagent');
var config = require('./superagent-mock-config');
var logger = function(log) {
console.log('superagent call', log);
};
var superagentMock = require('superagent-mock')(request, config, logger);
...
superagentMock.unset();
The callback function will be called with an object containing the following informations
- data : data used with
superagent.send
function
- headers : array of headers given by
superagent.set
function
- matcher : regex matching the current url which is defined in the provided config
- url : url which superagent was called
- method : HTTP method used for the call
- timestamp : timestamp of the superagent call
- mocked : true if the call was mocked by superagent mock, false if it used superagent real methods
Development scripts
To run units tests: yarn test
.
To check code style: yarn lint
.
To build code: yarn build
.
Credits
Developped by the Cytron Team of Bedrock Streaming.
Tested with Jest.
License
superagent-mock is licensed under the MIT license.