REST API mocker for the browsers. LOOK MA NO BACKEND! ๐
Written for superagent.
npm i superagent-mocker
var request = require('superagent');
var mock = require('superagent-mocker')(request);
You can provide custom timeout, that can be a function or a number. Just set
timeout
property to the mock
:
var mock = require('superagent-mocker');
// set just number
mock.timeout = 100;
// Or function to get random
mock.timeout = function () {
return Math.random() * 1e4 |0;
}
mock.get('/topics/:id', function(req) {
return {
id: req.params.id,
content: 'Hello World!'
};
});
request
.get('/topics/1')
.end(function(err, data) {
console.log(data); // { id: 1, content: 'Hello World' }
})
;
mock.post('/topics/:id', function(req) {
return {
id: req.params.id,
content: req.body.content
};
});
request
.post('/topics/5', { content: 'Hello world' })
.end(function(err, data) {
console.log(data); // { id: 5, content: 'Hello world' }
})
;
mock.put()
and mock.del()
methods works as well.
You can remove all of the route handlers by calling mock.clearRoutes()
. This is useful when defining temporary route handlers for unit tests.
// Using the mocha testing framework
define('My API module', function(){
beforeEach(function(){
// Guarentee each test knows exactly which routes are defined
mock.clearRoutes()
})
it('should GET /me', function(done){
mock.get('/me', function(){done()})
api.getMe()
})
it('should POST /me', function(done){
// The GET route handler no longer exists
// So there is no chance to see a false positive
// if the function actually calls GET /me
mock.post('/me', function(){done()})
api.saveMe()
})
})
Sadly, but request.send()
doesn't work :( Sorry
MIT ยฉ Shuvalov Anton