Skip to content

Medley plugin that augments an app to be able to make HTTP requests to itself for testing purposes

License

Notifications You must be signed in to change notification settings

medleyjs/self-request

Repository files navigation

@medley/self-request

npm Version Build Status Coverage Status dependencies Status

A Medley plugin that augments an app to be able to make HTTP requests to itself for testing purposes.

It adds a .request() method to the app that will start the app server and make HTTP requests to it using got.

Installation

npm install @medley/self-request --save-dev
# or
yarn add @medley/self-request --dev

Example Usage

app.js

const medley = require('@medley/medley');
const app = medley();

app.get('/', (req, res) => {
  res.send('Hello');
});

module.exports = app;

test.js

const assert = require('assert').strict;
const app = require('./app');

app.register(require('@medley/self-request'));

describe('app', () => {
  it('should say Hello', async () => {
    const res = await app.request('/');

    assert.equal(res.statusCode, 200);
    assert.equal(res.body, 'Hello');
  });
});

Plugin Options

gotDefaults

Type: Object

An object of got options that will be used as the defaults for each request.

These options will be merged in with the following defaults:

{
  retry: 0,
  timeout: 2000,
  followRedirect: false,
  throwHttpErrors: false,
  rejectUnauthorized: false,
  headers: {
    'user-agent': '@medley/self-request (https://github.com/medleyjs/self-request)',
  },
}

Example:

const medley = require('@medley/medley');
const app = medley();

app.get('/', (req, res) => {
  res.send({ hello: 'world' });
});

app.register(require('@medley/self-request'), {
  gotDefaults: {
    responseType: 'json',
  },
});

(async () => {
  const res = await app.request('/hello');
  console.log(res.body); // { hello: 'world' }
})();

API

app.request([url], [options])

Returns a Promise that resolves with a got response object.

Automatically calls app.listen() if the server is not already listening.

url

Type: string

The route URL to request.

app.request('/hello');

options

Type: Object

An object of got options.

app.request('/hello', {
  method: 'POST',
  body: 'Greetings',
});

app.request({
  url: '/hello',
  method: 'POST',
  body: 'Greetings',
});

Usage with sub-apps

If called on a prefixed sub-app, the url is relative to that sub-app.

const medley = require('@medley/medley');
const app = medley();

app.register(require('@medley/self-request'));

const v1App = app.createSubApp('/v1');

v1App.get('/hello', (req, res) => {
  res.send('Hello');
});

(async () => {
  const res = await v1App.request('/hello');
  console.log(res.body); // -> 'Hello'
})();

About

Medley plugin that augments an app to be able to make HTTP requests to itself for testing purposes

Resources

License

Stars

Watchers

Forks

Packages

No packages published