88 lines
2.3 KiB
TypeScript
88 lines
2.3 KiB
TypeScript
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
|
import { webrequest } from '../ts/index.js';
|
|
|
|
// test dependencies
|
|
import { TypedServer } from '@api.global/typedserver';
|
|
|
|
let testServer: TypedServer;
|
|
|
|
tap.test('setup test server', async () => {
|
|
testServer = new TypedServer({
|
|
cors: false,
|
|
forceSsl: false,
|
|
port: 2345,
|
|
});
|
|
|
|
testServer.addRoute('/apiroute1', 'GET', async (ctx) => {
|
|
return new Response(null, { status: 500 });
|
|
});
|
|
|
|
testServer.addRoute('/apiroute2', 'GET', async (ctx) => {
|
|
return new Response(null, { status: 500 });
|
|
});
|
|
|
|
testServer.addRoute('/apiroute3', 'GET', async (ctx) => {
|
|
return new Response(JSON.stringify({ hithere: 'hi' }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
});
|
|
|
|
await testServer.start();
|
|
});
|
|
|
|
tap.test('should handle fallback URLs', async () => {
|
|
const response = await webrequest(
|
|
'http://localhost:2345/apiroute1',
|
|
{
|
|
fallbackUrls: [
|
|
'http://localhost:2345/apiroute2',
|
|
'http://localhost:2345/apiroute3',
|
|
],
|
|
retry: {
|
|
maxAttempts: 3,
|
|
backoff: 'constant',
|
|
initialDelay: 100,
|
|
},
|
|
}
|
|
);
|
|
|
|
expect(response.ok).toEqual(true);
|
|
expect(response.status).toEqual(200);
|
|
const data = await response.json();
|
|
console.log('response with fallbacks: ' + JSON.stringify(data));
|
|
expect(data).toHaveProperty('hithere');
|
|
});
|
|
|
|
tap.test('should use getJson convenience method', async () => {
|
|
const data = await webrequest.getJson('http://localhost:2345/apiroute3');
|
|
console.log('getJson response: ' + JSON.stringify(data));
|
|
expect(data).toHaveProperty('hithere');
|
|
});
|
|
|
|
tap.test('should cache response', async () => {
|
|
// First request - goes to network
|
|
const response1 = await webrequest.getJson(
|
|
'http://localhost:2345/apiroute3',
|
|
{
|
|
cacheStrategy: 'cache-first',
|
|
}
|
|
);
|
|
expect(response1).toHaveProperty('hithere');
|
|
|
|
// Stop server
|
|
await testServer.stop();
|
|
|
|
// Second request - should use cache since server is down
|
|
const response2 = await webrequest.getJson(
|
|
'http://localhost:2345/apiroute3',
|
|
{
|
|
cacheStrategy: 'network-first', // Will fallback to cache on network error
|
|
}
|
|
);
|
|
expect(response2).toHaveProperty('hithere');
|
|
console.log('Cache fallback worked');
|
|
});
|
|
|
|
export default tap.start();
|