Mock out your API server for testing.
A flexible and powerful stand-in API server.
This server is meant to be booted quickly (for example, inside a test suite) in a Node.js process.
From the command-line:
./node_modules/.bin/mock-api-server --port PORT
To boot once for a test:
var MockApi = require'mock-api-server';var api = "port": 7000;apistart// ... do stuff ...apistop;
To connect to an existing server:
var MockApi = require'mock-api-server';var api = "port": 7000;apireset; // Or whatever you want to do.
test/server_test.coffee for more detailed examples.
If you are using Mocha, you can also boot the server in a
It's also possible to boot the server once at the beginning of the test
MockApi supports the following options:
|`port`||The IP port on which the mock server listens. Must be specified.|
|`logToConsole`||If `true`, requests will be logged to the console. Default: `false`.|
|`logToFile`||If set to a filename, requests will be logged to the specified file. If `null` or omitted, no file logging is done.|
Canned responses live in your project's
test/mock-api directory. This
directory and its subdirectories has the same structure as your API. For
example, to serve an endpoint
/v2/foobizzle, populate the file
Files in the
test/mock-api/GET subdirectory are used for GET requests. Files
test/mock-api/PUT subdirectory are used for PUT requests, and so forth.
If you have these three files:
test/mock-api/GET/v2/foobizzle.json test/mock-api/GET/v2/foobizzle.json?type=search test/mock-api/GET/v2/foobizzle.json?type=search&s=foo
mock-api-server will serve the third one when
are provided as query parameters. If only
type=search is provided, the second
one will be served--
mock-api-server will take the most specific matching file.
* can be used to match zero or more characters. For example, the following
Will match requests with a query parameter
type containing a value "search"
or "index,search" or "search,index".
Note that most shells will interpret
&, so to create these
files, you will have to backslash them. For example:
$ touch test/mock-api/GET/v2/foobizzle.json\?type=\*search\*\&s=foo
You can tell the API server to respond to a particular request like so:
This will be active until the next time
api.reset() is called.
You can modify an existing response with:
apirespondTo'/foo/bar'byReplacing'foo.bar.baz'with 76 ;