|
| 1 | +import { spawn } from 'child_process'; |
| 2 | + |
| 3 | +/* |
| 4 | + * Implementing plugin inline as a POC. This would be extracted to a separate |
| 5 | + * npm module following a pattern similar to @snowpack/web-test-runner-plugin: |
| 6 | + * https://github.com/snowpackjs/snowpack/tree/main/plugins/web-test-runner-plugin |
| 7 | + * or vite-web-test-runner-plugin: |
| 8 | + * https://github.com/betaboon/vite-web-test-runner-plugin |
| 9 | + */ |
| 10 | +const svelteKitPlugin = function () { |
| 11 | + let server; |
| 12 | + |
| 13 | + // quick hack; use more resilient approach in real plugin |
| 14 | + function randomPort(min = 49152, max = 65535) { |
| 15 | + return Math.floor(Math.random() * (max - min) + min); |
| 16 | + } |
| 17 | + |
| 18 | + // Currently, svelte-kit does not expose a method to the outside world to |
| 19 | + // start a dev server in JS-land. Work-around for POC: spawn a child process |
| 20 | + // that shells-out to svelte-kit cli. For real plugin, extract and export a |
| 21 | + // method from svelte-kit to start a dev server. |
| 22 | + function startTestServer(port) { |
| 23 | + const testServer = spawn('npx', ['svelte-kit', 'dev', `--port=${port}`]); |
| 24 | + |
| 25 | + testServer.stderr.on('data', (data) => { |
| 26 | + console.error(data.toString()); |
| 27 | + }); |
| 28 | + |
| 29 | + testServer.stdout.on('data', (data) => { |
| 30 | + console.log(data.toString()); |
| 31 | + }); |
| 32 | + |
| 33 | + return new Promise((resolve, reject) => { |
| 34 | + testServer.stdout.on('data', (data) => { |
| 35 | + if (/http:\/\/localhost:\d+/.test(data)) { |
| 36 | + resolve(testServer); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + testServer.on('close', reject); |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + return { |
| 45 | + name: 'svelte-kit-plugin', |
| 46 | + |
| 47 | + async serverStart({ app }) { |
| 48 | + const port = randomPort(); |
| 49 | + server = await startTestServer(port); |
| 50 | + app.use((ctx, next) => { |
| 51 | + ctx.redirect(`http://localhost:${port}${ctx.originalUrl}`); |
| 52 | + }); |
| 53 | + }, |
| 54 | + |
| 55 | + async serverStop() { |
| 56 | + return server.kill(); |
| 57 | + } |
| 58 | + }; |
| 59 | +}; |
| 60 | + |
| 61 | +process.env.NODE_ENV = 'test'; |
| 62 | + |
| 63 | +export default { |
| 64 | + plugins: [svelteKitPlugin()], |
| 65 | + testRunnerHtml: (testFramework) => ` |
| 66 | + <html> |
| 67 | + <head> |
| 68 | + <script> |
| 69 | + global = window; |
| 70 | + process = { env: { NODE_ENV: "test" } }; |
| 71 | + </script> |
| 72 | + <script type="module" src="${testFramework}"></script> |
| 73 | + </head> |
| 74 | + <body> |
| 75 | + <div id="svelte"></div> |
| 76 | + </body> |
| 77 | + </html> |
| 78 | + ` |
| 79 | +}; |
0 commit comments