All files / server/tests helpers.js

91.18% Statements 31/34
80% Branches 12/15
85.71% Functions 6/7
93.33% Lines 28/30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 669x 9x 9x 9x   9x     9x     9x     9x 41x 41x     9x     36x   36x         36x   36x 36x 36x 1x   35x 35x   36x       16x       9x             9x 7x 7x   7x     7x        
const request = require('request-promises');
const server = require('../server');
const port = require('./helpers/port');
const { get, post, put, del, error } = server.router;
 
exports.port = port;
 
// Just send 'Hello world' from the server side
exports.hello = ctx => ctx.res.send('Hello 世界');
 
// Make sure this method is never called
exports.err = ctx => { throw new Error('This should not be called'); };
 
 
exports.launch = launch = (middle = [], opts = {}) => {
  opts = Object.assign({}, { port: port() }, opts);
  return server(opts, middle);
};
 
exports.handler = async (middle, opts = {}, servOpts) => {
  // As they are loaded in parallel and from different files, we need to randomize it
  // The assuption here is under 100 tests/file
  const ctx = await launch(middle, servOpts);
 
  const options = Object.assign({}, {
    url: 'http://localhost:' + ctx.options.port + (opts.path || '/'),
    gzip: true
  }, opts);
 
  delete options.path;
 
  try {
    const res = await request(options);
    if (res.statusCode < 200 || res.statusCode >= 300) {
      throw new Error(`Invalid response code: ${res.statusCode}`);
    }
    ctx.close();
    return res;
  } finally {
    ctx.close();
  }
};
 
exports.getter = (middle, data = {}, opts, path = '/') => exports.handler(get(path, middle), {
  form: data
}, opts);
 
exports.poster = (middle, data = {}, opts) => exports.handler(post('/', middle), {
  form: data, method: 'POST'
}, opts);
 
 
 
// Handle a function that expects to be thrown
exports.throws = async (cb, err = false) => {
  try {
    const res = await cb();
  } catch(err) {
    Iif (!(err instanceof Error)) {
      throw new Error('A non-error was thrown: ' + err);
    }
    return err;
  }
  throw new Error('No error was thrown');
};