Skip to content

Commit

Permalink
Add support for waitForIt callback to be async (#255)
Browse files Browse the repository at this point in the history
* Bump to version 0.6.0

Closes #254
  • Loading branch information
chrisrohr committed Mar 21, 2024
1 parent 4156871 commit 62ddb32
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 6 deletions.
4 changes: 4 additions & 0 deletions __tests__/waitForIt/waitForIt.t.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ describe("WaitForIt", () => {
wait().until(() => true);
});

it("should resolve when condition passes and callback returns a promise", () => {
wait().until(() => Promise.resolve(true));
});

it("should reject when condition runs out of tries", async () => {
await expect(wait().until(() => false)).rejects.toEqual(
new Error("Condition was not met after 40 tries"),
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kiwiproject/kiwi-test-js",
"version": "0.5.1",
"version": "0.6.0",
"description": "kiwi-test-js is a test utility library. Most of these utilities are ports from the Java Kiwi-test library",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
17 changes: 14 additions & 3 deletions src/waitForIt/waitForIt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class WaitFor {
* will be returned.
* @param cb The function to check if the condition is true or false.
*/
until(cb: () => boolean): Promise<string> {
async until(cb: () => boolean | Promise<boolean>): Promise<string> {
const totalTries = this.timeoutMs / this.pollIntervalMs;

const aliasText = this.alias ? `with alias ${this.alias} ` : "";
Expand All @@ -91,8 +91,8 @@ class WaitFor {
return new Promise((resolve, reject) => {
let tries = 1;

const loop = () => {
if (cb.apply(this)) {
const processResult = (result: boolean) => {
if (result) {
if (this.verbose) {
console.log(
`Condition ${aliasText}met after ${tries} of ${totalTries} tries`,
Expand All @@ -118,6 +118,17 @@ class WaitFor {
}
};

const loop = async () => {
const cbResult = cb.apply(this);

if (typeof cbResult === "boolean") {
processResult(cbResult);
} else {
const cbPromiseResult = await cbResult;
processResult(cbPromiseResult);
}
};

if (this.pollDelayMs > 0) {
setTimeout(loop, this.pollDelayMs);
} else {
Expand Down

0 comments on commit 62ddb32

Please sign in to comment.