window-helpers.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const { expect } = require('chai');
  2. const { remote } = require('electron');
  3. const { BrowserWindow } = remote;
  4. const { emittedOnce } = require('./events-helpers');
  5. async function ensureWindowIsClosed (window) {
  6. if (window && !window.isDestroyed()) {
  7. if (window.webContents && !window.webContents.isDestroyed()) {
  8. // If a window isn't destroyed already, and it has non-destroyed WebContents,
  9. // then calling destroy() won't immediately destroy it, as it may have
  10. // <webview> children which need to be destroyed first. In that case, we
  11. // await the 'closed' event which signals the complete shutdown of the
  12. // window.
  13. const isClosed = emittedOnce(window, 'closed');
  14. window.destroy();
  15. await isClosed;
  16. } else {
  17. // If there's no WebContents or if the WebContents is already destroyed,
  18. // then the 'closed' event has already been emitted so there's nothing to
  19. // wait for.
  20. window.destroy();
  21. }
  22. }
  23. }
  24. exports.closeWindow = async (window = null,
  25. { assertSingleWindow } = { assertSingleWindow: true }) => {
  26. await ensureWindowIsClosed(window);
  27. if (assertSingleWindow) {
  28. // Although we want to assert that no windows were left handing around
  29. // we also want to clean up the left over windows so that no future
  30. // tests fail as a side effect
  31. const currentId = remote.getCurrentWindow().id;
  32. const windows = BrowserWindow.getAllWindows();
  33. for (const win of windows) {
  34. if (win.id !== currentId) {
  35. await ensureWindowIsClosed(win);
  36. }
  37. }
  38. expect(windows).to.have.lengthOf(1);
  39. }
  40. };
  41. exports.waitForWebContentsToLoad = async (webContents) => {
  42. const didFinishLoadPromise = emittedOnce(webContents, 'did-finish-load');
  43. if (webContents.isLoadingMainFrame()) {
  44. await didFinishLoadPromise;
  45. }
  46. };