50 lines
1.9 KiB
JavaScript
50 lines
1.9 KiB
JavaScript
import test from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { readFileSync } from 'node:fs'
|
|
import ts from 'typescript'
|
|
import { computed, ref } from 'vue'
|
|
|
|
function setup() {
|
|
const requests = []
|
|
const source = readFileSync(new URL('./notifications.ts', import.meta.url), 'utf8').replace(/^import [^\r\n]*\r?\n/gm, '').replace('export const', 'const')
|
|
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
|
const store = new Function('computed', 'ref', 'defineStore', 'getMyUnreadNotificationCount', code + '\nreturn useNotificationsStore()')(computed, ref, (_id, factory) => factory, () => new Promise((resolve, reject) => requests.push({ resolve, reject })))
|
|
return { store, requests }
|
|
}
|
|
|
|
test('shell and page concurrent reads share one pending request', async () => {
|
|
const { store, requests } = setup()
|
|
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount()
|
|
assert.equal(requests.length, 1)
|
|
requests[0].resolve(5)
|
|
await Promise.all([a, b])
|
|
assert.equal(store.unreadCount.value, 5)
|
|
assert.equal(store.loading.value, false)
|
|
})
|
|
|
|
test('post-mutation refresh reads again after a pending pre-mutation read', async () => {
|
|
const { store, requests } = setup()
|
|
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount(true)
|
|
assert.equal(requests.length, 1)
|
|
requests[0].resolve(5)
|
|
await a
|
|
await Promise.resolve()
|
|
assert.equal(requests.length, 2)
|
|
requests[1].resolve(0)
|
|
await b
|
|
assert.equal(store.unreadCount.value, 0)
|
|
})
|
|
|
|
test('failed request releases the pending guard for retry', async () => {
|
|
const { store, requests } = setup()
|
|
const a = store.refreshUnreadCount()
|
|
requests[0].reject(new Error('network'))
|
|
await a
|
|
const b = store.refreshUnreadCount()
|
|
assert.equal(requests.length, 2)
|
|
requests[1].resolve(2)
|
|
await b
|
|
assert.equal(store.unreadCount.value, 2)
|
|
assert.equal(store.errorMessage.value, '')
|
|
})
|