Add package @cosmjs/utils
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
export function assert(condition: any, msg?: string): asserts condition {
|
||||
if (!condition) {
|
||||
throw new Error(msg || "condition is not truthy");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { assert } from "./assert";
|
||||
export { sleep } from "./sleep";
|
||||
@@ -0,0 +1,27 @@
|
||||
import { sleep } from "./sleep";
|
||||
|
||||
describe("sleep", () => {
|
||||
it("resolves after at least x milliseconds", async () => {
|
||||
for (const x of [10, 30, 120, 280]) {
|
||||
const start = Date.now();
|
||||
await sleep(x);
|
||||
const sleepingTime = Date.now() - start;
|
||||
|
||||
// Add 1 ms safety margin due to rounding issues. The elapsed time between
|
||||
// timestamps 1000 and 1010 can be somethting between 10 and 11 ms.
|
||||
expect(sleepingTime + 1).toBeGreaterThanOrEqual(x);
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves within a reasonable amount of time >= x milliseconds", async () => {
|
||||
// Don't be too strict as jest will run many tests at the same time and test systems can be slow sometimes.
|
||||
const tolerance = 30; // ms
|
||||
|
||||
for (const x of [10, 30, 120, 280]) {
|
||||
const start = Date.now();
|
||||
await sleep(x);
|
||||
const sleepingTime = Date.now() - start;
|
||||
expect(sleepingTime).toBeLessThanOrEqual(x + tolerance);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export async function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
Reference in New Issue
Block a user