Skip to content

Commit

Permalink
refactor: improve test setup, rename existing test (#79)
Browse files Browse the repository at this point in the history
* refactor: improve test setup, rename existing test

* fix: lint
  • Loading branch information
braaar authored Feb 12, 2024
1 parent c8737e8 commit 1655094
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 221 deletions.
97 changes: 0 additions & 97 deletions src/__snapshots__/abax-client.spec.ts.snap

This file was deleted.

29 changes: 0 additions & 29 deletions src/abax-client.spec.ts

This file was deleted.

95 changes: 0 additions & 95 deletions src/abax-client.test.ts

This file was deleted.

73 changes: 73 additions & 0 deletions src/rate-limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { addMilliseconds } from 'date-fns';
import { describe, expect, it } from 'vitest';
import { initialiseClientAndMockPool } from './test-utils';

describe('rate-limit-handling', () => {
const { client, mockPool } = initialiseClientAndMockPool();

it('should time out when getting 429', async () => {
mockPool
.intercept({
path: '/v1/vehicles',
method: 'GET',
})
.reply(() => ({
statusCode: 429,
responseOptions: {
headers: {
'X-Rate-Limit-Reset': addMilliseconds(
new Date(),
100,
).toISOString(),
},
},
}))
.times(4);

await expect(() => client.listVehicles()).rejects.toThrow(
'Request timed out',
);
});

it('should retry thrice when getting 429', async () => {
mockPool
.intercept({
path: '/v1/vehicles',
method: 'GET',
})
.reply(() => ({
statusCode: 429,
responseOptions: {
headers: {
'X-Rate-Limit-Reset': addMilliseconds(
new Date(),
100,
).toISOString(),
},
},
}))
.times(3);

mockPool
.intercept({
path: '/v1/vehicles',
method: 'GET',
})
.reply(() => ({
statusCode: 200,
data: {
page: 1,
page_size: 150,
items: [],
},
}))
.times(1);

const vehicles = await client.listVehicles();
expect(vehicles).toEqual({
items: [],
page: 1,
page_size: 150,
});
});
});
20 changes: 20 additions & 0 deletions src/test-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { type Interceptable, MockAgent, setGlobalDispatcher } from 'undici';
import { AbaxClient } from './abax-client';

export function initialiseClientAndMockPool(): {
client: AbaxClient;
mockPool: Interceptable;
} {
const mockAgent = new MockAgent();
mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);

const mockPool = mockAgent.get('https://api.abax.cloud');

const client = new AbaxClient({
baseUrl: 'production',
apiKey: 'kanonball!',
});

return { client, mockPool };
}

0 comments on commit 1655094

Please sign in to comment.