59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
import { test } from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { AxiosError } from 'axios'
|
|
import { extractErrorMessage } from '../src/shared/api/http.ts'
|
|
|
|
function makeAxiosError(status: number, data: unknown) {
|
|
return new AxiosError('Request failed with status code ' + status, String(status), undefined, undefined, {
|
|
status,
|
|
data,
|
|
statusText: '',
|
|
headers: {},
|
|
config: {} as never,
|
|
})
|
|
}
|
|
|
|
test('test_extract_error_field', () => {
|
|
const error = makeAxiosError(400, { error: '字段校验失败' })
|
|
assert.equal(extractErrorMessage(error), '字段校验失败')
|
|
})
|
|
|
|
test('test_extract_message_field', () => {
|
|
const error = makeAxiosError(500, { message: '服务器内部错误' })
|
|
assert.equal(extractErrorMessage(error), '服务器内部错误')
|
|
})
|
|
|
|
test('test_extract_msg_field', () => {
|
|
const error = makeAxiosError(400, { msg: '任务已存在' })
|
|
assert.equal(extractErrorMessage(error), '任务已存在')
|
|
})
|
|
|
|
test('test_extract_error_precedence', () => {
|
|
const error = makeAxiosError(400, { error: 'e1', message: 'm1', msg: 'm2' })
|
|
assert.equal(extractErrorMessage(error), 'e1', 'error 应优先')
|
|
|
|
const noError = makeAxiosError(400, { message: 'm1', msg: 'm2' })
|
|
assert.equal(extractErrorMessage(noError), 'm1', '无 error 时 message 优先于 msg')
|
|
})
|
|
|
|
test('test_extract_string_body', () => {
|
|
const error = makeAxiosError(502, 'Bad Gateway 网关错误')
|
|
assert.equal(extractErrorMessage(error), 'Bad Gateway 网关错误')
|
|
})
|
|
|
|
test('test_extract_fallback_message', () => {
|
|
const error = makeAxiosError(500, {})
|
|
assert.equal(extractErrorMessage(error), 'Request failed with status code 500')
|
|
})
|
|
|
|
test('test_extract_axios_non_error', () => {
|
|
assert.equal(extractErrorMessage(new Error('普通错误')), '普通错误')
|
|
assert.equal(extractErrorMessage('纯字符串'), '请求失败')
|
|
assert.equal(extractErrorMessage(undefined), '请求失败')
|
|
})
|
|
|
|
test('test_extract_blank_values_skipped', () => {
|
|
const error = makeAxiosError(400, { error: ' ', message: '', msg: '真实原因' })
|
|
assert.equal(extractErrorMessage(error), '真实原因', '空白 error/message 应跳过,回退 msg')
|
|
})
|