_test_functions.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict'
  2. import path from 'path'
  3. import express from 'express'
  4. import WebSocket from 'ws'
  5. import serveStatic from 'serve-static'
  6. import routes from '../../server/routes'
  7. import { apiPrefix, imageServedUrl, imagesPath } from '../../config'
  8. import connectDb from '../../server/database'
  9. import { errorHandler as wsErrorHandler } from '../../server/webSocket'
  10. import wsMessageHandler from '../../server/webSocket/messageHandler'
  11. // Path to `test` directory
  12. export const testDir = path.resolve(__dirname, '..')
  13. // Pretty-print a JSON object
  14. export const json = obj => 'JSON DATA : ' + (JSON.stringify(obj, null, 2) || obj)
  15. /**
  16. * @typedef PluginConfig
  17. * @property {boolean} [webSocket=false] should the server start with a WebSocket server
  18. * @property {boolean} [database=false] should the server start with a WebSocket server
  19. */
  20. /**
  21. * Open an Express server not listening to any port.
  22. * The server serves images in `test/images`, all api routes and
  23. * uses a custom error handler (no logging to stdout).
  24. *
  25. * Using `request` (supertest) on this object will start the server
  26. * on an ephemeral port.
  27. * @param {PluginConfig} plugins plugins that should be loaded with the server
  28. * @returns {object} an Express server
  29. */
  30. const serve = async (plugins = { webSocket: false, database: false }) => {
  31. // Connect to db
  32. if (plugins && plugins.database) await connectDb()
  33. // Open a HTTP server
  34. const app = express()
  35. app.use(imageServedUrl, serveStatic(imagesPath))
  36. app.use(apiPrefix, routes)
  37. app.use((err, req, res, next) => {
  38. res.status(err.output.payload.statusCode).json({
  39. message: err.message || err.output.payload.message,
  40. data: err.data || undefined
  41. })
  42. })
  43. // Open a WebSocket server
  44. if (plugins && plugins.webSocket) {
  45. const wss = new WebSocket.Server({ server: app })
  46. wss.on('error', err => {
  47. throw err
  48. })
  49. wss.on('connection', ws => {
  50. ws.on('message', data => wsMessageHandler(ws)(data).catch(wsErrorHandler(ws)))
  51. ws.on('error', wsErrorHandler(ws))
  52. })
  53. }
  54. return app
  55. }
  56. // Pass a server to test context
  57. export const getTestServer = async (t, plugins) => (t.context.server = await serve(plugins))