Micro Router Test Server- A tiny test server for microrouter and Zeit's micro
- Async. Designed for usage with
async
andawait
- Simple. Test routes on a local live server.
- Tiny. < 60 lines of code.
- Independent. No reliance on specific testing frameworks.
Node 7+
Install as dev dependency
yarn install microrouter-test-server -D
Write 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);
});
routes
- an array of routes returned by the route methods (get
,post
,put
,del
,patch
,head
andoptions
) 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)
uri
is the relative path to the routeoptions
is the configuration object forrequest
/request-promise
- methods return a promise ala request-promise
- Closes the active connection to the test server.
const result = await server.post('/route2', {
json: true,
body: { my: 'payload' },
});
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:
server.post('/route')
.then(body => {
// 2xx status
})
.catch(err => {
console.log(err.statusCode);
})
const response = await server.post('/route', {
simple: false,
resolveWithFullResponse: true,
});
if (response.statusCode == 200) {
doSomething(response);
} else {
handleFailure();
}