aboutsummaryrefslogtreecommitdiffstats
path: root/test/runner/createTestServer.js
blob: ebc6bd4bbd4e9df346b30ae9443e45841d3ec092 (plain)
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
import bodyParser from "body-parser";
import express from "express";
import bodyParserErrorHandler from "express-body-parser-error-handler";
import fs from "fs";
import mockServer from "../middleware-mockserver.cjs";

export async function createTestServer( report ) {
	const nameHTML = await fs.promises.readFile( "./test/data/name.html", "utf8" );
	const indexHTML = await fs.promises.readFile( "./test/index.html", "utf8" );
	const app = express();

	// Redirect home to test page
	app.get( "/", ( _req, res ) => {
		res.redirect( "/test/" );
	} );

	// Redirect to trailing slash
	app.use( ( req, res, next ) => {
		if ( req.path === "/test" ) {
			const query = req.url.slice( req.path.length );
			res.redirect( 301, `${ req.path }/${ query }` );
		} else {
			next();
		}
	} );

	// Add a script tag to the index.html to load the QUnit listeners
	app.use( /\/test(?:\/index.html)?\//, ( _req, res ) => {
		res.send( indexHTML.replace(
			"</head>",
			"<script src=\"/test/runner/listeners.js\"></script></head>"
		) );
	} );

	// Bind the reporter
	app.post( "/api/report", bodyParser.json( { limit: "50mb" } ), ( req, res ) => {
		if ( report ) {
			report( req.body );
		}
		res.sendStatus( 204 );
	} );

	// Handle errors from the body parser
	app.use( bodyParserErrorHandler() );

	// Hook up mock server
	app.use( mockServer() );

	// Serve static files
	app.post( "/test/data/name.html", ( _req, res ) => {
		res.send( nameHTML );
	} );

	app.use( "/dist", express.static( "dist" ) );
	app.use( "/src", express.static( "src" ) );
	app.use( "/test", express.static( "test" ) );
	app.use( "/external", express.static( "external" ) );

	return app;
}