Build: Bump the github-actions group with 2 updates
[jquery.git] / test / runner / createTestServer.js
blob8021db40fd056140669624b24570bc436a598e70
1 import bodyParser from "body-parser";
2 import express from "express";
3 import bodyParserErrorHandler from "express-body-parser-error-handler";
4 import { readFile } from "node:fs/promises";
5 import mockServer from "../middleware-mockserver.cjs";
7 export async function createTestServer( report ) {
8         const nameHTML = await readFile( "./test/data/name.html", "utf8" );
9         const indexHTML = await readFile( "./test/index.html", "utf8" );
10         const app = express();
12         // Redirect home to test page
13         app.get( "/", ( _req, res ) => {
14                 res.redirect( "/test/" );
15         } );
17         // Redirect to trailing slash
18         app.use( ( req, res, next ) => {
19                 if ( req.path === "/test" ) {
20                         const query = req.url.slice( req.path.length );
21                         res.redirect( 301, `${ req.path }/${ query }` );
22                 } else {
23                         next();
24                 }
25         } );
27         // Add a script tag to the index.html to load the QUnit listeners
28         app.use( /\/test(?:\/index.html)?\//, ( _req, res ) => {
29                 res.send(
30                         indexHTML.replace(
31                                 "</head>",
32                                 "<script src=\"/test/runner/listeners.js\"></script></head>"
33                         )
34                 );
35         } );
37         // Bind the reporter
38         app.post(
39                 "/api/report",
40                 bodyParser.json( { limit: "50mb" } ),
41                 async( req, res ) => {
42                         if ( report ) {
43                                 const response = await report( req.body );
44                                 if ( response ) {
45                                         res.json( response );
46                                         return;
47                                 }
48                         }
49                         res.sendStatus( 204 );
50                 }
51         );
53         // Handle errors from the body parser
54         app.use( bodyParserErrorHandler() );
56         // Hook up mock server
57         app.use( mockServer() );
59         // Serve static files
60         app.post( "/test/data/name.html", ( _req, res ) => {
61                 res.send( nameHTML );
62         } );
64         app.use( "/dist", express.static( "dist" ) );
65         app.use( "/src", express.static( "src" ) );
66         app.use( "/test", express.static( "test" ) );
67         app.use( "/external", express.static( "external" ) );
69         return app;