Created
October 2, 2019 10:05
-
-
Save lukeshumard/08a10b1644098a88c9c211fabb6f2d03 to your computer and use it in GitHub Desktop.
Getting @now/node helpers with tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { send } = require('micro'); | |
module.exports = async (req, res) => { | |
try { | |
const query = req.query; | |
send(res, 200, query); | |
} catch (err) { | |
send(res, 500); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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