Add package @cosmjs/utils

This commit is contained in:
Simon Warta
2020-06-09 17:40:42 +02:00
parent 92417373cd
commit e582313b17
18 changed files with 224 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
export function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new Error(msg || "condition is not truthy");
}
}
+2
View File
@@ -0,0 +1,2 @@
export { assert } from "./assert";
export { sleep } from "./sleep";
+27
View File
@@ -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);
}
});
});
+3
View File
@@ -0,0 +1,3 @@
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}