nomadro/apps/miniprogram/weapp/scripts/test-social.cjs
Eric f20406397a Harden social UX and APIs: idempotent chat/join, config cache, weapp polish.
Improve hall chat retries, meetup-live lifecycle, home/mine remote-config UX, and add isolated social/API regression tests without deploying.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 14:00:11 +08:00

76 lines
4.7 KiB
JavaScript

// All network/storage/socket behavior is mocked. Never calls a production service.
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const ts = require('typescript')
const root = path.resolve(__dirname, '../../h5/src/services')
function harness(file, overrides = {}, imports = {}) {
const storage = new Map()
const taro = { getStorageSync: key => storage.get(key), setStorageSync: (key, value) => storage.set(key, value), ...overrides }
const module = { exports: {} }
const code = ts.transpileModule(fs.readFileSync(path.join(root, file), 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2018, esModuleInterop: true } }).outputText
const stubs = { '@tarojs/taro': taro, '@/utils/config': { API_BASE: 'https://api.invalid', WEB_BASE: 'https://web.invalid' }, ...imports }
vm.runInNewContext(code, { module, exports: module.exports, require: id => { if (!(id in stubs)) throw Error(id); return stubs[id] }, setTimeout, clearTimeout })
return { api: module.exports, storage }
}
test('reads fail over and subsequent writes use the successful origin', async () => {
const urls = []
const { api } = harness('socialApi.ts', { request: async options => { urls.push(options.url); return { statusCode: urls.length === 1 ? 503 : 200, data: { items: [], id: 'saved' } } } })
await api.socialApi.listMessages('general')
await api.socialApi.sendMessage('general', 'Name', 'Hello', 'key')
assert.equal(urls.length, 3)
assert.ok(urls[2].startsWith('https://api.nomadro.cn/'))
})
test('uncertain message writes never replay across origins', async () => {
let count = 0
const { api } = harness('socialApi.ts', { request: async () => { count++; throw Error('timeout') } })
await assert.rejects(api.socialApi.sendMessage('general', 'Name', 'Hello', 'key'))
assert.equal(count, 1)
})
test('permission errors never fail over even on reads', async () => {
let count = 0
const { api } = harness('socialApi.ts', { request: async () => { count++; return { statusCode: 403, data: { detail: 'Denied' } } } })
await assert.rejects(api.socialApi.listMessages('general'), /Denied/)
assert.equal(count, 1)
})
test('failed applications retain one idempotency key across explicit retries', async () => {
const keys = []
const { api } = harness('socialApi.ts', { request: async options => { keys.push(options.data.requestId); return { statusCode: keys.length === 1 ? 503 : 200, data: { id: 'saved' } } } })
const payload = { name: 'Name', contact: 'Contact' }
await assert.rejects(api.socialApi.applyGig('gig', payload))
await api.socialApi.applyGig('gig', payload)
assert.equal(keys[0], keys[1])
assert.equal(api.getLocalApply('gig').delivery, 'sent')
})
test('chat snapshots retain newer messages and reconcile a realtime acknowledgement', () => {
const { api } = harness('socialChatState.ts')
const local = { id: 'local', clientId: 'key', text: 'Hello', at: '2026-11-02', channelId: 'general', guestId: 'me', delivery: 'pending' }
const ack = { ...local, id: 'saved' }
let result = api.mergeChatMessages([local], [ack], 'me')
assert.equal(result.length, 1)
assert.equal(result[0].delivery, 'sent')
result = api.mergeChatMessages(result, [], 'me')
assert.equal(result[0].id, 'saved')
})
test('socket reports live only after subscribe and unwraps backend publication envelopes', async () => {
const handlers = {}, commands = [], delivered = [], states = []
const task = { onOpen: fn => handlers.open = fn, onMessage: fn => handlers.message = fn, onError: fn => handlers.error = fn, onClose: fn => handlers.close = fn, send: ({data}) => commands.push(JSON.parse(data)), close: () => {} }
const { api } = harness('socialRealtime.ts', { connectSocket: () => task }, { './socialApi': { socialApi: { realtimeToken: async () => ({ ok: true, enabled: true, token: 'mock', wsUrl: 'wss://socket.invalid/ws', channel: 'social:general' }) } } })
const pending = api.connectChatRealtime('general', item => delivered.push(item), state => states.push(state))
await new Promise(resolve => setImmediate(resolve))
handlers.open()
assert.ok(commands[0].connect)
handlers.message({ data: JSON.stringify({ id: 1, connect: {} }) })
assert.ok(commands[1].subscribe)
assert.equal(states.length, 0)
handlers.message({ data: JSON.stringify({ id: 2, subscribe: {} }) })
const connection = await pending
assert.equal(states[0], true)
handlers.message({ data: JSON.stringify({ push: { pub: { data: { type: 'chat.message', message: { id: 'saved', channelId: 'general', text: 'Hello' } } } } }) })
assert.equal(delivered[0].id, 'saved')
connection.disconnect()
assert.equal(states[1], false)
})