Skip to content

Commit

Permalink
test: add waitForTrue to avoid flaky visibilityState test
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelmaddock committed Apr 21, 2021
1 parent ec9fe90 commit 9c5ae84
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 6 deletions.
10 changes: 4 additions & 6 deletions spec-main/api-web-frame-main-spec.ts
Expand Up @@ -6,6 +6,7 @@ import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain } from 'electron/mai
import { closeAllWindows } from './window-helpers';
import { emittedOnce, emittedNTimes } from './events-helpers';
import { AddressInfo } from 'net';
import { waitForTrue } from './spec-helpers';

describe('webFrameMain module', () => {
const fixtures = path.resolve(__dirname, '..', 'spec-main', 'fixtures');
Expand Down Expand Up @@ -143,12 +144,9 @@ describe('webFrameMain module', () => {

expect(webFrame.visibilityState).to.equal('visible');
w.hide();

// Wait for visibility to propagate. If this ends up being flaky, we can
// look into binding WebContentsObserver::OnVisibilityChanged.
await new Promise(resolve => setTimeout(resolve, 10));

expect(webFrame.visibilityState).to.equal('hidden');
await expect(
waitForTrue(() => webFrame.visibilityState === 'hidden')
).to.eventually.be.fulfilled();
});
});

Expand Down
46 changes: 46 additions & 0 deletions spec-main/spec-helpers.ts
Expand Up @@ -86,3 +86,49 @@ export async function startRemoteControlApp () {
defer(() => { appProcess.kill('SIGINT'); });
return new RemoteControlApp(appProcess, port);
}

export function waitForTrue (
callback: () => boolean,
opts: { rate?: number, timeout?: number } = {}
) {
const { rate = 10, timeout = 10000 } = opts;
return new Promise<void>((resolve, reject) => {
let intervalId: NodeJS.Timeout | undefined; // eslint-disable-line prefer-const
let timeoutId: NodeJS.Timeout | undefined;

const cleanup = () => {
if (intervalId) clearInterval(intervalId);
if (timeoutId) clearTimeout(timeoutId);
};

const check = () => {
let result;

try {
result = callback();
} catch (e) {
cleanup();
reject(e);
return;
}

if (result === true) {
cleanup();
resolve();
}
return result;
};

if (check()) {
return;
}

intervalId = setInterval(check, rate);

timeoutId = setTimeout(() => {
timeoutId = undefined;
cleanup();
reject(new Error(`waitForTrue timed out after ${timeout}ms`));
}, timeout);
});
}

0 comments on commit 9c5ae84

Please sign in to comment.