_test_functions.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict'
  2. import path from 'path'
  3. import express from 'express'
  4. import serveStatic from 'serve-static'
  5. import routes from '../../server/routes'
  6. import { apiPrefix, imageServedUrl, imagesPath } from '../../config'
  7. // Path to `test` directory
  8. export const testDir = path.resolve(__dirname, '..')
  9. // Pretty-print a JSON object
  10. export const json = obj => 'JSON DATA : ' + (JSON.stringify(obj, null, 2) || obj)
  11. /**
  12. * Uses supertest to open an Express server on an ephemeral port.
  13. * The server serves images in `test/images`, all api routes and
  14. * uses a custom error handler (no logging to stdout).
  15. *
  16. * Using `request` (supertest) on this object will start the server
  17. *
  18. * @returns {object} an Express server
  19. */
  20. export const serve = () => {
  21. const app = express()
  22. app.use(imageServedUrl, serveStatic(imagesPath))
  23. app.use(apiPrefix, routes)
  24. app.use((err, req, res, next) => {
  25. res.status(err.output.payload.statusCode).json({
  26. message: err.message || err.output.payload.message,
  27. data: err.data || undefined
  28. })
  29. })
  30. return app
  31. }
  32. // Before each tests, start a server
  33. export const beforeEachTests = async t => {
  34. t.context.server = serve()
  35. }