32 lines
1.5 KiB
JavaScript
32 lines
1.5 KiB
JavaScript
const assert = require('node:assert/strict')
|
|
const { test } = require('node:test')
|
|
const fs = require('node:fs')
|
|
const path = require('node:path')
|
|
const ts = require('typescript')
|
|
|
|
test('request with no platform callback ends at 10 seconds and aborts without retrying', async () => {
|
|
const timers = new Map()
|
|
let calls = 0
|
|
let aborted = 0
|
|
let resolve
|
|
const task = new Promise(r => { resolve = r })
|
|
task.abort = () => { aborted++ }
|
|
const module = { exports: {} }
|
|
const source = fs.readFileSync(path.join(__dirname, '../src/services/api.ts'), 'utf8')
|
|
const js = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2019, esModuleInterop: true } }).outputText
|
|
new Function('require', 'module', 'exports', 'setTimeout', 'clearTimeout', js)(name => {
|
|
if (name === '@tarojs/taro') return { request: () => { calls++; return task } }
|
|
if (name === '@/config/env') return { API_BASE_URL: 'https://example.invalid' }
|
|
return { getToken: () => 'test', getCurrentUserId: () => 7, handleUnauthorized: () => {} }
|
|
}, module, module.exports, (fn, ms) => { timers.set(fn, ms); return fn }, fn => timers.delete(fn))
|
|
const pending = module.exports.request('/test')
|
|
const [timer, duration] = [...timers][0]
|
|
assert.equal(duration, 10000)
|
|
timer()
|
|
await assert.rejects(pending, /请求超时/)
|
|
assert.equal(aborted, 1)
|
|
assert.equal(calls, 1)
|
|
assert.equal(timers.size, 0)
|
|
resolve({ statusCode: 200, data: {} })
|
|
})
|