Skip to content

Instantly share code, notes, and snippets.

@corlaez
Last active March 4, 2019 02:03
Show Gist options
  • Save corlaez/cca37bc2a2f72712c207ff0b58e3febf to your computer and use it in GitHub Desktop.
Save corlaez/cca37bc2a2f72712c207ff0b58e3febf to your computer and use it in GitHub Desktop.
Serverless Api Test Client

Serverless Api Test Client

While working with zeit now serverless functions I needed to execute my apis locally (they connected to a db and processed the data) and see if they work correctly

This code allows you to execute any api and just logs or ignores the result of the api. Useful for manual checks but could be expanded to run automated tests as well.

What I like is that you can test any api just importing the api and instanciating a client. The requests are JavaScript objects and that makes it very natural and simple to read and write api tests.

The heart of the client creator is the createExecutor higher order function, that's the real MVP.

Requirements

You will need node js to run this example

How to run

Open your terminal/cmd and execute:

npx https://gist.github.com/lrn2prgrm/cca37bc2a2f72712c207ff0b58e3febf
// take a request object and convert it to url params, sweet!
const toUrlParams = (request) => Object.keys(request).map(
key => `${key}=${request[key]}`,
).join('&')
// Take a request object and transform it to a full url with params. The endpoint is irrelevant
const toUrl = (request) => 'https://example.com?' + toUrlParams(request)
// end function that finishes execution and returns a value to the client
// api is the serverless function we want to execute
// url is where we get the url params from
const createExecutor = (api, end) => request => api({ url: toUrl(request) }, { end });
const createApiClient = api => {
return {
// A method that prints whatever was passed to the end method
log: createExecutor(api, console.log),
// A method that just executes the api and ignores the param passed to end.
silent: createExecutor(api, () => {}),
}
}
module.exports = createApiClient
{
"name": "npx-serverless-api-test-client",
"version": "0.0.1",
"bin": "./serverless-function.test.js"
}
const { parse } = require('url')
const serverlessFunction = (httpReq, httpRes) => {
const { country } = parse(httpReq.url, true).query
httpRes.end('Welcome to ' + country) // httpReq.end(response)
}
module.exports = serverlessFunction
#!/usr/bin/env node
const createApiClient = require('./create-api-client')
const serverlessFunction = require('./serverless-function')
const client = createApiClient(serverlessFunction)
// object queries
const successRequest = {
country: 'Aruba'
}
// executions
client.log(successRequest) // Prints 'Welcome to Aruba'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment