Trek_CN/server/tests/unit/services/amap/amap.client.test.ts
2026-07-11 15:48:47 +08:00

65 lines
2.2 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AmapClient } from '../../../../src/services/amap/amap.client';
describe('AmapClient', () => {
const originalKey = process.env.AMAP_WEB_SERVICE_KEY;
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn());
delete process.env.AMAP_WEB_SERVICE_KEY;
});
afterEach(() => {
vi.unstubAllGlobals();
if (originalKey === undefined) delete process.env.AMAP_WEB_SERVICE_KEY;
else process.env.AMAP_WEB_SERVICE_KEY = originalKey;
});
it('returns a configuration error without AMAP_WEB_SERVICE_KEY', async () => {
const client = new AmapClient();
await expect(client.get('/v3/place/text', new URLSearchParams())).rejects.toMatchObject({
code: 'AMAP_NOT_CONFIGURED',
status: 503,
});
expect(fetch).not.toHaveBeenCalled();
});
it('uses the fixed AMap host and appends the server-only key', async () => {
process.env.AMAP_WEB_SERVICE_KEY = 'secret-web-key';
vi.mocked(fetch).mockResolvedValue(
new Response(JSON.stringify({ status: '1', pois: [] }), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
);
await new AmapClient().get('/v3/place/text', new URLSearchParams({ keywords: 'beijing' }));
const url = new URL(String(vi.mocked(fetch).mock.calls[0]?.[0]));
expect(url.origin).toBe('https://restapi.amap.com');
expect(url.pathname).toBe('/v3/place/text');
expect(url.searchParams.get('keywords')).toBe('beijing');
expect(url.searchParams.get('key')).toBe('secret-web-key');
});
it('redacts the key from provider failures', async () => {
process.env.AMAP_WEB_SERVICE_KEY = 'secret-web-key';
vi.mocked(fetch).mockResolvedValue(
new Response(JSON.stringify({ status: '0', info: 'INVALID_USER_KEY', infocode: '10001' }), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
);
try {
await new AmapClient().get('/v3/place/text', new URLSearchParams());
throw new Error('expected request to fail');
} catch (err) {
expect(err).toMatchObject({ code: 'AMAP_PROVIDER_ERROR', status: 502 });
expect(String((err as Error).message)).not.toContain('secret-web-key');
}
});
});