• Stars
    star
    255
  • Rank 159,227 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Copy API endpoints to your fs and run a local server using them

snapstub logo

snapstub

NPM version GitHub Actions License

Snapshot-based stub/mocking of APIs

Small command line tool that allows you to take "snapshots" of any given API endpoint and store the response. Using the start command will spawn a server that will serve all previously stored endpoints.

Heavily inspired by Jest Snapshot testing

Table of Contents

Install

npm install -g snapstub

Usage

Make sure you're in the desired folder to host your api mock files.

⬇️ Creates a new api stub:

snapstub add http://example.com/api/foo/bar

...create as many snapshots as you want.

πŸš€ Starts your mock server:

snapstub start

✨ Your endpoint will be locally available at: http://localhost:8059/api/foo/bar


Advanced Usage

Using different http methods

If you want to save one or many different http methods, use the --method option:

snapstub add http://example.com/api/foo/bar --method=get,post,put

Using custom headers to add a new route

If you need to pass a custom header along with your request, let's say one is needed for a auth token or any other reason, use the --header option:

snapstub add http://example.com/api/user/42 --header "X-Token: 1234"

You can set as many custom headers as you need:

snapstub add http://example.com/api/login --header "X-User: foo" --header "X-Token: bar"

Using html or plain text

In order to save or add a html or plain text endpoint a --nojson flag must be specified in order to bypass json encode/decode:

snapstub add http://example.com/html --nojson

Sending data when adding a new route

Usually a POST/PUT method will also require data to be sent along with the request, you can do so by using the --data option:

snapstub add http://example.com/api/user/new --data "name=Foo"

Content-Type headers will be set automatically but if you specify one (using --header option) that will take precedence.

It also accepts json data (Content-Type will be set to application/json automatically):

snapstub add http://example.com/api/user/new --data '{ "name": "Lorem" }'

If no method is defined it defaults to POST, if you want to use PUT instead just use the --method option:

snapstub add http://example.com/api/user/update --data "name=Bar" --method=put

Sending data read from a file

You can also point the --data option to a file in order to use the contents of that file as a payload. This is a good way to maintain repeatable calls to POST/PUT routes. Given that there is a payload.json file in the current working directory:

snapstub add http://example.com/api/user/add --data ./payload.json

Headers will be automatically added and the content will be exactly as read from the file.

Saving standard input data into a new endpoint

This is a very useful workflow that allows you to combine Chrome's Copy as cURL web dev tools option with the ability to store a snapstub route.

curl http://example.com/api/foo | snapstub save /api/foo

or you can just save any arbitrary data:

cat foo.json | snapstub save /api/foo # similar to $ cp foo.json __mocks__/api/foo

or even:

echo '{"data":true}' | snapstub save /api/foo

Deterministic mocks using query-string or headers

snapstub provides out of the box support to deterministic mocking by using query-string, headers, cookies thanks to request-hash. Deterministic results for those cases will create a file name suffixed by a unique hash which snapstub uses in order to serve the correct value when using the snapstub start server.

Deterministic results for query strings in the urls is active by default, for headers or cookies however you'll need to configure which values you'll want to use in order to create the unique hash. It can be set using the --hashHeaders or --hashCookies options:

snapstub add http://example.com/api/user/42 --header "X-Token: 1234" --hashHeaders=x-token
βœ”  Successfully added: __mocks__/api/user/42/get-491db12454c89a51646710b06bc6c51f9d45.json

Both --hashHeaders and --hashCookies accepts a comma-separated list of keys.

Customizing hash algorithm

The algorithm used to create the unique hash can also be customized using the --hashAlgorithm option.

Change defaults

Using custom port and/or folder name:

export SNAPSTUB_FOLDER_NAME=my-mock-folder/
export SNAPSTUB_PORT=9000
snapstub start

More info

By default snapshots will be saved in a __mocks__ folder that resolves from the current working directory, so make sure you run the commands from the correct project folder you desire.


Programmatic API

A JavaScript programmatic api is available if you're using node.js:

const snapstub = require('snapstub');

// starts the mock server
snapstub.start({
	verbose: true,
	mockFolderName: '__mocks__',
	port: 8080
});

The following methods are available, please note all values used are just example values meant to ilustrate a common usage:

add(opts)

snapstub.add({
	url: 'http://example.com/api/v1/data',
	addOptions: {
		headers: {
			'content-type': 'application/json',
			'Cookie': 'FOO=bar;'
		},
		body: 'lorem=ipsum',
		method: 'post'
	},
	mockFolderName: '__mocks__'
});

save(opts)

snapstub.save({
	url: '/api/v1/data',
	saveOptions: {
		data: { foo: 'bar' },
		headers: { 'X-Foo': 'bar' },
		hashAlgorithm: 'sha256',
		hashHeaders: ['x-foo'],
		hashCookies: [],
		method: 'post',
		nojson: false
	},
	mockFolderName: '__mocks__'
});

start(opts)

snapstub.start({
	hashAlgorithm: 'sha256',
	hashHeaders: ['x-foo'],
	hashCookies: [],
	verbose: true,
	mockFolderName: '__mocks__',
	port: 8080
});

stop()

snapstub.stop();

Credits

  • Logo: Camera by Simon Child from the Noun Project
  • snapstub wouldn't be possible without stubborn-server - it's a very flexible mock server based on static files, if you have the need to handle more complex scenarios (handling route params, dynamic responses, etc) go take a look at it.

Maintainers

Contribute

Please do! This is an open source project. If you would like a feature, open a pull request. If you have a bug or want to discuss something, open an issue.

License

MIT Β© Ruy Adorno

More Repositories

1

ntl

Node Task List: Interactive cli to list and run package.json scripts
JavaScript
888
star
2

ipt

Interactive Pipe To: The Node.js cli interactive workflow
JavaScript
843
star
3

simple-slider

🎠 The 1kb JavaScript Carousel
JavaScript
601
star
4

dom-i18n

Provides a very basic HTML multilingual support using JavaScript
JavaScript
139
star
5

grunt-menu

Useful menu interface for listing/executing your configured tasks
JavaScript
79
star
6

installme-osx

My personal script to setup a new OSX
Shell
60
star
7

git-bc

Git plugin to interactively list branches and checkout
JavaScript
60
star
8

generator-umd

An Yeoman Generator to create a basic UMD structure
JavaScript
28
star
9

console-faker

Get some file content to be printed out on console while you type anything on your keyboard.
JavaScript
26
star
10

preact-jest-snapshot-test-boilerplate

πŸš€ Test Preact components using Jest snapshots
JavaScript
23
star
11

mitro-cli

Manage your Mitro passwords from a command line interface.
JavaScript
22
star
12

telegram-pi-bot

A python-telegram-bot setup to run on Raspberry pi
Python
22
star
13

polymer-simple-slider

A Polymer element providing a simple slider functionality
HTML
22
star
14

jest-serializer-html-string

A better Jest snapshot serializer for plain html strings
JavaScript
17
star
15

prettierme

Fastest way to run prettier for a single file. Fork of https://github.com/ruyadorno/eslintme
Shell
15
star
16

angular-simple-slider

An AngularJS directive providing a simple slider functionality
JavaScript
15
star
17

checkbower

Validates your bower.json files
JavaScript
13
star
18

itrash

Interactively selects files to delete from current folder in the cli
JavaScript
13
star
19

git-iadd

Git plugin that allows you to interactively select which files to add to stage (git add)
JavaScript
12
star
20

dotfiles

Shell
11
star
21

mail-sender

A simple python script to send an html email using smtplib
Python
10
star
22

clean-dir

Command line util to clean a directory
JavaScript
9
star
23

request-hash

Generate a hash from an express Request or http.IncomingMessage
JavaScript
8
star
24

path-complete-extname

path.extname implementation adapted to also include multiple dots extensions.
JavaScript
8
star
25

eslintme

The fastest way to eslint a single file
Shell
7
star
26

extract-path

Extract a valid file system path from a string
JavaScript
7
star
27

lru-cache-fs

Extends lru-cache to add file system support
JavaScript
6
star
28

estimate

Application to help time estimation for digital agencies.
Python
5
star
29

js-signals-factory

A small factory implementation for js-signals.
JavaScript
5
star
30

git-pr

Interactive checkout PRs using the GitHub cli
Shell
4
star
31

git-ishow

Git plugin that lets you interactively select a stashed item to show
JavaScript
4
star
32

tlr

Quick spawn a tiny-lr server
JavaScript
4
star
33

nextjs-api-fetch-example

A simple example using fetched API data to render components
JavaScript
4
star
34

simple-output

Output messages to stdout/stderr
JavaScript
4
star
35

extend-grunt-plugin

Helper method to easily extend an already existing grunt task.
JavaScript
4
star
36

create-100-workshop

The road to 100% test coverage workshop
JavaScript
3
star
37

npx-utils

πŸ‘Ύ Manages packages in the npx-space
JavaScript
3
star
38

simple-data-structures

πŸŒ… Basic data structures with tons of tests and helper functions
Python
2
star
39

cli-all-the-things

Talk at ForwardJS 2020
JavaScript
2
star
40

npm-community-landing-page

HTML
2
star
41

outdated

Shortcut to interactively update an outdated dep using npm + ipt
Shell
1
star
42

redact

Small cli util that redacts path refs from stdin
JavaScript
1
star
43

stubborn-server-hash-loader

Loader plugin for stubborn-server
JavaScript
1
star
44

ruyadorno.github.io

HTML
1
star
45

mitro-js

Mirror of the API to access Mitro server side from node applications.
JavaScript
1
star
46

vim-change-indent

Vim plugin to convert the indent sizes in a file.
Vim Script
1
star
47

ruyadorno

1
star
48

generator-jsmontreal

A test generator to be presented at js-montreal 02/10 meetup
JavaScript
1
star
49

checkgituser

Checks a folder to find .git/config files without an [user] field declared
Python
1
star
50

the-one-with-test-coverage

Demo repo for my test coverage talk from JS Montreal 10/2019
JavaScript
1
star