Files
webrequest/test/test.ts

98 lines
2.4 KiB
TypeScript
Raw Normal View History

import { expect, tap } from '@git.zone/tstest/tapbundle';
import { webrequest } from '../ts/index.js';
2018-12-04 17:35:40 +01:00
2018-12-03 18:35:30 +01:00
// test dependencies
2023-08-27 16:33:10 +02:00
import * as typedserver from '@api.global/typedserver';
2018-12-03 18:35:30 +01:00
2023-07-09 17:24:52 +02:00
let testServer: typedserver.servertools.Server;
2018-12-03 18:35:30 +01:00
tap.test('setup test server', async () => {
2023-07-09 17:24:52 +02:00
testServer = new typedserver.servertools.Server({
2018-12-03 18:35:30 +01:00
cors: false,
forceSsl: false,
2020-10-09 10:14:45 +00:00
port: 2345,
2018-12-03 18:35:30 +01:00
});
testServer.addRoute(
'/apiroute1',
2023-07-09 17:24:52 +02:00
new typedserver.servertools.Handler('GET', (req, res) => {
res.status(429);
res.end();
}),
);
2018-12-03 18:35:30 +01:00
testServer.addRoute(
'/apiroute2',
2023-07-09 17:24:52 +02:00
new typedserver.servertools.Handler('GET', (req, res) => {
res.status(500);
res.end();
}),
);
2018-12-04 17:35:40 +01:00
testServer.addRoute(
'/apiroute3',
2023-07-09 17:24:52 +02:00
new typedserver.servertools.Handler('GET', (req, res) => {
res.status(200);
res.send({
2020-10-09 10:14:45 +00:00
hithere: 'hi',
});
}),
);
2018-12-04 17:35:40 +01:00
2019-06-04 15:23:47 +02:00
await testServer.start();
});
2018-12-03 18:35:30 +01:00
tap.test('should handle fallback URLs', async () => {
const response = await webrequest(
'http://localhost:2345/apiroute1',
{
fallbackUrls: [
2023-02-12 17:54:00 +01:00
'http://localhost:2345/apiroute2',
'http://localhost:2345/apiroute4',
'http://localhost:2345/apiroute3',
],
retry: {
maxAttempts: 3,
backoff: 'constant',
initialDelay: 100,
},
}
);
2019-09-27 20:16:28 +02:00
const data = await response.json();
console.log('response with fallbacks: ' + JSON.stringify(data));
expect(data).toHaveProperty('hithere');
});
2018-12-04 17:35:40 +01:00
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');
});
2018-12-04 17:35:40 +01:00
2022-05-29 20:22:42 +02:00
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
2022-05-29 20:22:42 +02:00
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
}
);
2022-05-29 20:22:42 +02:00
expect(response2).toHaveProperty('hithere');
console.log('Cache fallback worked');
2023-02-12 17:54:00 +01:00
});
2018-11-30 17:12:48 +01:00
export default tap.start();