readiness
v1.0.1
Published
Checks whether a service at a given url is responsive
Downloads
8
Readme
readiness
A small utility module to check if a service is up and running at a given url.
Overview
Often when testing your code against dependent (micro)services, it's required to defer the test run until a given dependency is up and running - usually meaning it responds with a 2XX HTTP status-code at a dedicated health-check endpoint. Since services tend to have a relatively long starup time (imagine a JVM-based, dockerized service started as a test-dependency), it's often required to attempt the readiness call at given intervals for a certain period of time to allow the service to start-up and respond.
Using Readiness in tests
Whether you're using Jest or Mocha, using readiness looks quite the same. I'll use Jest to demonstrate:
const {readiness} = require('readiness')
describe('My code is awesome', () => {
beforeAll(() => {
await readiness('http://some-other-service/is_ready');
});
test('Other code - not so', () => {
expect(fetch('http://localhost:3030/my-service')).resolves.toEqual(true));
});
});
The call to readiness
makes sure the the other service we depend on is ready (in the default use-case, responds with a 2XX status-code), and only then resolves the promise that signals beforeAll()
to complete.
Options
readiness
supports additional options that control the check procedure, and can be passed as a second argument to the readiness
function:
readiness('http://localhost:3000', options)
options.attempts
- the number of attempts to call the service before it's declared unavailble, rejecting the promise. Defaults to 1.options.interval
- the interval (in milliseconds) between consequent attempts to invoke the service. Effective only whenoptions.attempts
is greater than 1, and defaults to 200ms.options.customCheck
- a custom function that allows overriding the default readiness-check logic. Accepts thenode-fetch
response as an input, and expected to resolve if the response is considered to be from a healthy service, or reject otherwise. An example use-case is when you consider a service ready if it returns a 401 response code, since you cannot or does not want to authenticate against the health-check endpoint.
const {readiness} = require('readiness')
describe('My code is awesome', () => {
beforeAll(() => {
await readiness('http://some-other-service/is_ready', {
customCheck: async (response) => {
const isUnauthorized = response.status === 401;
const body = await response.json();
return isUnauthorized && body.error === 'unauthorized' ? Promise.resolve() : Promise.reject();
}
});
});
test('Other code - not so', () => {
expect(fetch('http://localhost:3030/my-service')).resolves.toEqual(true)); // Succeeds, even though the service responded with a non-2XX code - due to the customCheck implementation
});
});