56 lines
2.7 KiB
JavaScript
56 lines
2.7 KiB
JavaScript
import test from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { createSession } from '../src/session.mjs'
|
|
|
|
const response = (data, status = 200) => ({ ok: status < 400, status, json: async () => ({ data, msg: '导入失败' }) })
|
|
function setup() {
|
|
const pending = []
|
|
const session = createSession({ fetch: (url, options) => new Promise(resolve => pending.push({ url, options, resolve })), storage: { getItem() {}, setItem() {}, removeItem() {} } })
|
|
session.state.user = { id: 1, username: 'fixture.admin', role: 'admin' }
|
|
session.state.token = 'fictional-test-token'
|
|
return { session, pending }
|
|
}
|
|
|
|
test('dictionary upload sends multipart with authorization and lets browser set boundary', async () => {
|
|
const { session, pending } = setup()
|
|
const form = new FormData()
|
|
form.append('name', 'Princeton WordNet')
|
|
form.append('file', new Blob(['fictional-archive']), 'wordnet.zip')
|
|
assert.equal(typeof session.importDictionary, 'function')
|
|
const request = session.importDictionary(form)
|
|
assert.equal(pending[0].url, '/api/v1/dictionaries/import')
|
|
assert.equal(pending[0].options.method, 'POST')
|
|
assert.equal(pending[0].options.body, form)
|
|
assert.equal(pending[0].options.headers['Content-Type'], undefined)
|
|
assert.equal(pending[0].options.headers.Authorization, 'Bearer fictional-test-token')
|
|
pending[0].resolve(response({ resource: { id: 1 }, duplicate: false }))
|
|
assert.deepEqual(await request, { resource: { id: 1 }, duplicate: false })
|
|
})
|
|
|
|
test('dictionary read and toggle follow API contract, ordinary accounts cannot mutate', async () => {
|
|
const { session, pending } = setup()
|
|
assert.equal(typeof session.listDictionaries, 'function')
|
|
const read = session.listDictionaries()
|
|
assert.equal(pending[0].url, '/api/v1/dictionaries')
|
|
pending[0].resolve(response({ items: [] }))
|
|
await read
|
|
const toggle = session.setDictionaryEnabled(1, false)
|
|
assert.equal(pending[1].url, '/api/v1/dictionaries/1')
|
|
assert.deepEqual(JSON.parse(pending[1].options.body), { enabled: false })
|
|
pending[1].resolve(response({ resource: { id: 1, enabled: false } }))
|
|
await toggle
|
|
session.state.user.role = 'learner'
|
|
await assert.rejects(session.importDictionary(new FormData()), /管理员/)
|
|
await assert.rejects(session.setDictionaryEnabled(1, true), /管理员/)
|
|
assert.equal(pending.length, 2)
|
|
})
|
|
|
|
test('dictionary response cannot cross a logout or account switch', async () => {
|
|
const { session, pending } = setup()
|
|
assert.equal(typeof session.importDictionary, 'function')
|
|
const request = session.importDictionary(new FormData())
|
|
session.clear()
|
|
pending[0].resolve(response({ resource: { id: 1 }, duplicate: false }))
|
|
await assert.rejects(request, /会话已变化/)
|
|
})
|