// The Chores page script: it draws the page from real server data without throwing (a thrown error here leaves the page on "Loading…"). const fs = require('fs'), vm = require('vm'), path = require('path'), assert = require('assert'), { Readable } = require('stream'); process.env.DATA_DIR = fs.mkdtempSync(path.join(require('os').tmpdir(), 'nehub-crview-')); const users = require('../users'), chores = require('../chores'); const ann = users.create({ name: 'Ann', role: 'admin', handle: 'YQ' }), bob = users.create({ name: 'Bob', role: 'user', tabs: ['chores'], handle: 'Yg' }); const run = (url, method = 'GET', body) => new Promise(ok => { const q = Readable.from(body ? [Buffer.from(JSON.stringify(body))] : []); q.url = url; q.method = method; q.headers = {}; users.runAs(ann, () => chores.handle(q, { writeHead() {}, end: d => ok(JSON.parse(d)) })); }); (async () => { try { await run('/api/chores', 'POST', { title: 'Dishes', repeat: 'daily', assign: [bob.id], points: 3 }); await run('/api/chores', 'POST', { title: 'Trash', repeat: 'daily', assign: 'anyone', points: 2 }); await run('/api/chores/reward', 'POST', { title: 'Movie', points: 3 }); const today = new Date().toISOString().slice(0, 10), data = await run('/api/chores?date=' + today), week = await run('/api/chores/week?date=' + today); let html = ''; const el = { set innerHTML(v) { html = v; }, get innerHTML() { return html; }, querySelectorAll: () => ({ forEach() {} }), querySelector: () => null }; const ctx = { ME: { id: ann.id, role: 'admin' }, location: { hash: '#/chores' }, document: {}, console, Intl, $: s => s === '#view' ? el : new Proxy({}, { get: () => () => {}, set: () => true }), esc: s => String(s), icon: () => '', sgColor: () => '#000', sgInitial: s => s[0], jfetch: async u => u.includes('/week') ? week : data, toast() {}, openSheet: () => el, closeSheet() {}, confirmSheet() {}, allowed: () => true }; vm.createContext(ctx); vm.runInContext(fs.readFileSync(path.join(__dirname, '../public/chores-view.js'), 'utf8'), ctx); await vm.runInContext('viewChores()', ctx); assert.ok(/Weekly goals/.test(html) && /Dishes/.test(html) && /Take it/.test(html), 'the page is drawn with chores, a Take it button and the weekly goals'); console.log('chores view ok'); } catch (e) { console.error(e); process.exitCode = 1; } process.exit(process.exitCode || 0); })();