OverviewFilesCommitsIssuesDocsReleasesPeers

cthuloid / android / test / worklet.test.js

44 lines · javascript ref:
// The worklet entry, run under desktop Bare (no BareKit): it must serve the page
// from the EMBEDDED assets and the controller API, and reuse its port on restart.
import test from 'brittle'
import http from 'bare-http1'
import fs from 'bare-fs'
import os from 'bare-os'
import path from 'bare-path'

globalThis.CTHULOID_NO_AUTOSTART = true
const { start } = await import('../lib/worklet.js')

const STATIC = path.join(path.dirname(new URL(import.meta.url).pathname), '..', '..', 'webui', 'static')

function get (url) {
  return new Promise((resolve, reject) => {
    http.request(url, (res) => {
      const chunks = []
      res.on('data', (d) => chunks.push(d))
      res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString() }))
    }).on('error', reject).end()
  })
}

test('serves the page from embedded assets and the API', async (t) => {
  const storage = path.join(os.tmpdir(), 'cthuloid-worklet-' + Date.now())
  const { app, url } = await start(storage)
  t.ok(/^http:\/\/127\.0\.0\.1:\d+\/$/.test(url), url)
  const page = await get(url)
  t.is(page.status, 200)
  t.is(page.body, fs.readFileSync(path.join(STATIC, 'index.html'), 'utf8'), 'page = static/index.html')
  const st = await get(url + 'api/state')
  t.is(JSON.parse(st.body).connected, false, 'starts disconnected')
  await app.close()
})

test('a restart reuses the port, so the WebView URL survives', async (t) => {
  const storage = path.join(os.tmpdir(), 'cthuloid-worklet-' + Date.now() + '-r')
  const a = await start(storage)
  await a.app.close()
  const b = await start(storage)
  t.is(b.url, a.url)
  await b.app.close()
})