• Stars
    star
    132
  • Rank 274,205 (Top 6 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pretty simple in-browser mocks for CRUD and REST API

superagent-mocker

Build Status Coverage Status npm version npm downloads

REST API mocker for the browsers. LOOK MA NO BACKEND! 👐

Written for superagent.

Install

npm i superagent-mocker

Usage

Setup

var request = require('superagent');
var mock = require('superagent-mocker')(request);

Timeout

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;
}

Get

You may set headers using the mock.set(). To ensure header keys are not case sensitive, all keys will be transformed to lower case (see example).

mock.get('/topics/:id', function(req) {
  return {
    id: req.params.id,
    content: 'Hello World!',
    headers: req.headers
  };
});

request
  .get('/topics/1')
  .set({ 'X-Custom-Header': 'value of header' })
  .end(function(err, data) {
    console.log(data); // { id: 1, content: 'Hello World', headers: { 'x-custom-header': 'value of header' } }
  })
;

mock.del() works in a similar way.

Post

You may set the body of a POST request as the second parameter of mock.post() or in mock.send(). Values set in send() will overwrite previously set values.

mock.post('/topics/:id', function(req) {
  return {
    id: req.params.id,
    body: req.body
  };
});

request
  .post('/topics/5', {
    content: 'I will be overwritten',
    fromPost: 'Foo'
  })
  .send({
    content: 'Hello world',
    fromSend: 'Bar'
  })
  .end(function(err, data) {
    console.log(data); // { id: 5, body: { content: 'Hello world', fromPost: 'Foo', fromSend: 'Bar' } }
  })
;

mock.put(), mock.patch() methods works in a similar way.

Teardown

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()
  })

})

Or you can remove only one specified route (by method and url)

// to register route
mock.get('/me', function(){done()})

...

// to remove registered handler
mock.clearRoute('get', '/me');

Rollback library effect

In some cases it will be useful to remove patches from superagent lib after using mocks. In this cases you can use mock.unmock(superagent) method, that will rollback all patches that mock(superagent) call make.

License

MIT © Shuvalov Anton

More Repositories

1

largescaleJS_ru

Russian translation of Addy Osmani book.
Stylus
626
star
2

code-screenshots

Скриншоты редакторов кода разных разработчиков
227
star
3

textr

Modular typographic framework
JavaScript
183
star
4

.dotfiles

configs and utils
Lua
80
star
5

obsidian-blog

Static site/blog generator for obsidian.md
Python
38
star
6

node-clusterize-cli

The simplest CLI interface for clusterize and demonize your apps
JavaScript
27
star
7

vim-trash-polka

Dark & Light Theme for Vim and ITerm2 inspired by @arcticicestudio/Nord.
Vim Script
14
star
8

go-search-me

Open your browser from terminal to search things
Go
10
star
9

superagent-django-csrf

Patch to add `csrftoken` from cookies as `X-CSRFToken` header to every superagent's request
JavaScript
8
star
10

to-ms

Tiny chained ms creation util for NodeJS and browsers
JavaScript
7
star
11

obsidian-blog-theme

CSS
5
star
12

dela

CLI to list markdown todos
Python
4
star
13

shuvalov.info

My blog
HTML
4
star
14

client-rest-framework

REST API framework to construct domain API repositories
TypeScript
3
star
15

repo-manager

Opinionated wrapper around git clone, that keeps all your repos in structure
TypeScript
3
star
16

parcel-plugin-peer-dependencies

Parcel plugin to exclude peer dependencies. Should be useful with yarn workspaces.
JavaScript
3
star
17

mnml-tpl

Hello :username, :repository is tiny string template engine
JavaScript
3
star
18

ansible_docker_compose

3
star
19

docker-compose-kafka

2
star
20

docker_compose_node_exporter

2
star
21

docker_compose_traefik

2
star
22

sofle

C
2
star
23

next-done

It's just countdowns your callbacks.
JavaScript
2
star
24

zapusk

Job runner for developers and desktop users supports configured jobs, shell-command execution, scheduling and notifications
Python
2
star
25

zettelkasten-sublime

Sublime Text 3 Plugin that creates timestamped notes in the given folder
Python
1
star
26

your-moms-twitbot

Ugly and nervous bot for twitter
JavaScript
1
star
27

node-smsc

Poorly SMSC API implementation
JavaScript
1
star
28

unsplash_dl

Unsplash collection downloader
Python
1
star
29

local-traefik

1
star