1.0.3 • Published 8 years ago
microrouter-test-server v1.0.3
Micro Router Test Server- A tiny test server for microrouter and Zeit's micro
Features
- Async. Designed for usage with
asyncandawait - Simple. Test routes on a local live server.
- Tiny. < 60 lines of code.
- Independent. No reliance on specific testing frameworks.
Pre-requisites
Node 7+
Usage
Install as dev dependency
yarn install microrouter-test-server -DWrite a test (with Jest)
// routes.test.js
const { get, post, put } = require('microrouter');
const { json, send } = require('micro');
const { createServer } = require('microrouter-test-server');
const routes = [
get('/route1', () => 'route1'),
post('/route2', req => json(req)),
put('/route3', (req, res) => send(res, 400, 'route3')),
];
let server;
beforeAll(async () => {
server = await createServer(routes);
});
afterAll(async () => {
await server.close();
});
test('GET of route1 should return expected value', async () => {
const result = await server.get('/route1');
expect(result).toEqual('route1');
});
test('POST to route2 should return the payload', async () => {
const payload = { abc: 123 };
const result = await server.post('/route2', {
json: true,
body: payload,
});
expect(result).toEqual(payload);
});
test('PUT to route3 should reject with non-2xx status', async () => {
await expect(server.put('/route3')).rejects.toHaveProperty('statusCode', 400);
});API
async createServer(routes = Array<microrouter-route>)
routes- an array of routes returned by the route methods (get,post,put,del,patch,headandoptions) ofmicrorouter- returns
Promise<Object>with methods:get(uri: String, options: RequestOptions)post(uri: String, options: RequestOptions)put(uri: String, options: RequestOptions)del(uri: String, options: RequestOptions)patch(uri: String, options: RequestOptions)head(uri: String, options: RequestOptions)uriis the relative path to the routeoptionsis the configuration object forrequest/request-promise- methods return a promise ala request-promise
async close()
- Closes the active connection to the test server.
Examples
POST a payload
const result = await server.post('/route2', {
json: true,
body: { my: 'payload' },
});Handle non-2xx responses
microrouter-test-server uses request-promise to handle requests. By default, this library rejects on any status other than a 2xx. Here's a few ways to handle it:
.catch(StatusCodeError)
server.post('/route')
.then(body => {
// 2xx status
})
.catch(err => {
console.log(err.statusCode);
})Get the full response object
const response = await server.post('/route', {
simple: false,
resolveWithFullResponse: true,
});
if (response.statusCode == 200) {
doSomething(response);
} else {
handleFailure();
}