Skip to content

Instantly share code, notes, and snippets.

@lukeshumard
Created October 2, 2019 10:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeshumard/08a10b1644098a88c9c211fabb6f2d03 to your computer and use it in GitHub Desktop.
Save lukeshumard/08a10b1644098a88c9c211fabb6f2d03 to your computer and use it in GitHub Desktop.
Getting @now/node helpers with tests
const micro = require('micro');
// taken directly from
// https://github.com/zeit/now-builders/blob/f67480a98ac461dc2fe6bb27e8a4ea86e9b6b60a/packages/now-node/src/helpers.ts#L47-L60
function queryParser({ url = '/' }) {
const { URL } = require('url');
// we provide a placeholder base url because we only want searchParams
const params = new URL(url, 'https://n').searchParams;
const query = {};
for (const [key, value] of params) {
query[key] = value;
}
return query;
}
const wrappedMicro = (route) => micro(async (req, res) => {
req.query = queryParser(req);
return await route(req, res);
});
module.exports = wrappedMicro;
const { send } = require('micro');
module.exports = async (req, res) => {
try {
const query = req.query;
send(res, 200, query);
} catch (err) {
send(res, 500);
}
};
// This example is using Jest
const listen = require('test-listen');
const fetch = require('isomorphic-unfetch');
const route = require('./route');
const server = require('./helper');
describe('A cool test', () => {
it('Will have @now/node request.query helper', async () => {
const service = server(route);
const url = await listen(service);
const res = await fetch(`${url}?test=working`);
const body = await (res => res.json())(res);
expect(res.status).toBe(200);
expect(body).toEqual({ 'test': "working" });
service.close();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment