Browse Source

test: convert a few more specs to async/await (#40313)

Milan Burda 1 year ago
parent
commit
67894f1493

+ 4 - 8
spec/api-debugger-spec.ts

@@ -29,16 +29,12 @@ describe('debugger module', () => {
       expect(w.webContents.debugger.isAttached()).to.be.true();
     });
 
-    it('fails when protocol version is not supported', done => {
-      try {
-        w.webContents.debugger.attach('2.0');
-      } catch {
-        expect(w.webContents.debugger.isAttached()).to.be.false();
-        done();
-      }
+    it('fails when protocol version is not supported', () => {
+      expect(() => w.webContents.debugger.attach('2.0')).to.throw();
+      expect(w.webContents.debugger.isAttached()).to.be.false();
     });
 
-    it('attaches when no protocol version is specified', async () => {
+    it('attaches when no protocol version is specified', () => {
       w.webContents.debugger.attach();
       expect(w.webContents.debugger.isAttached()).to.be.true();
     });

+ 7 - 4
spec/api-power-monitor-spec.ts

@@ -11,6 +11,7 @@ import * as dbus from 'dbus-native';
 import { ifdescribe, startRemoteControlApp } from './lib/spec-helpers';
 import { promisify } from 'node:util';
 import { setTimeout } from 'node:timers/promises';
+import { once } from 'node:events';
 
 describe('powerMonitor', () => {
   let logindMock: any, dbusMockPowerMonitor: any, getCalls: any, emitSignal: any, reset: any;
@@ -77,17 +78,19 @@ describe('powerMonitor', () => {
     });
 
     describe('when PrepareForSleep(true) signal is sent by logind', () => {
-      it('should emit "suspend" event', (done) => {
-        dbusMockPowerMonitor.once('suspend', () => done());
+      it('should emit "suspend" event', async () => {
+        const suspend = once(dbusMockPowerMonitor, 'suspend');
         emitSignal('org.freedesktop.login1.Manager', 'PrepareForSleep',
           'b', [['b', true]]);
+        await suspend;
       });
 
       describe('when PrepareForSleep(false) signal is sent by logind', () => {
-        it('should emit "resume" event', done => {
-          dbusMockPowerMonitor.once('resume', () => done());
+        it('should emit "resume" event', async () => {
+          const resume = once(dbusMockPowerMonitor, 'resume');
           emitSignal('org.freedesktop.login1.Manager', 'PrepareForSleep',
             'b', [['b', false]]);
+          await resume;
         });
 
         it('should have called Inhibit again', async () => {

+ 1 - 1
spec/api-web-contents-spec.ts

@@ -1615,7 +1615,7 @@ describe('webContents module', () => {
             response.end();
             break;
           default:
-            done('unsupported endpoint');
+            done(new Error('unsupported endpoint'));
         }
       });
       listen(server).then(({ url }) => {

+ 1 - 2
spec/chromium-spec.ts

@@ -8,7 +8,6 @@ import * as fs from 'node:fs';
 import * as url from 'node:url';
 import * as ChildProcess from 'node:child_process';
 import { EventEmitter, once } from 'node:events';
-import { promisify } from 'node:util';
 import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
 import { PipeTransport } from './pipe-transport';
 import * as ws from 'ws';
@@ -2514,7 +2513,7 @@ describe('font fallback', () => {
 });
 
 describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
-  const fullscreenChildHtml = promisify(fs.readFile)(
+  const fullscreenChildHtml = fs.promises.readFile(
     path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
   );
   let w: BrowserWindow;

+ 11 - 12
spec/extensions-spec.ts

@@ -3,7 +3,7 @@ import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session }
 import { closeAllWindows, closeWindow } from './lib/window-helpers';
 import * as http from 'node:http';
 import * as path from 'node:path';
-import * as fs from 'node:fs';
+import * as fs from 'node:fs/promises';
 import * as WebSocket from 'ws';
 import { emittedNTimes, emittedUntil } from './lib/events-helpers';
 import { ifit, listen } from './lib/spec-helpers';
@@ -200,7 +200,7 @@ describe('chrome extensions', () => {
 
   it('serializes a loaded extension', async () => {
     const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
-    const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
+    const manifest = JSON.parse(await fs.readFile(path.join(extensionPath, 'manifest.json'), 'utf-8'));
     const customSession = session.fromPartition(`persist:${uuid.v4()}`);
     const extension = await customSession.loadExtension(extensionPath);
     expect(extension.id).to.be.a('string');
@@ -684,16 +684,15 @@ describe('chrome extensions', () => {
           let server: http.Server;
           let port: number;
           before(async () => {
-            server = http.createServer((_, res) => {
-              fs.readFile(contentPath, (error, content) => {
-                if (error) {
-                  res.writeHead(500);
-                  res.end(`Failed to load ${contentPath} : ${error.code}`);
-                } else {
-                  res.writeHead(200, { 'Content-Type': 'text/html' });
-                  res.end(content, 'utf-8');
-                }
-              });
+            server = http.createServer(async (_, res) => {
+              try {
+                const content = await fs.readFile(contentPath, 'utf-8');
+                res.writeHead(200, { 'Content-Type': 'text/html' });
+                res.end(content, 'utf-8');
+              } catch (error) {
+                res.writeHead(500);
+                res.end(`Failed to load ${contentPath} : ${(error as NodeJS.ErrnoException).code}`);
+              }
             });
 
             ({ port, url } = await listen(server));

+ 1 - 1
spec/node-spec.ts

@@ -873,7 +873,7 @@ describe('node feature', () => {
       });
     };
 
-    process.once('unhandledRejection', () => done('catch block is delayed to next tick'));
+    process.once('unhandledRejection', () => done(new Error('catch block is delayed to next tick')));
 
     setTimeout(() => {
       f3().catch(() => done());

+ 14 - 23
spec/security-warnings-spec.ts

@@ -1,6 +1,6 @@
 import { expect } from 'chai';
 import * as http from 'node:http';
-import * as fs from 'node:fs';
+import * as fs from 'node:fs/promises';
 import * as path from 'node:path';
 import * as url from 'node:url';
 
@@ -27,36 +27,27 @@ describe('security warnings', () => {
 
   before(async () => {
     // Create HTTP Server
-    server = http.createServer((request, response) => {
+    server = http.createServer(async (request, response) => {
       const uri = url.parse(request.url!).pathname!;
       let filename = path.join(__dirname, 'fixtures', 'pages', uri);
 
-      fs.stat(filename, (error, stats) => {
-        if (error) {
-          response.writeHead(404, { 'Content-Type': 'text/plain' });
-          response.end();
-          return;
-        }
-
+      try {
+        const stats = await fs.stat(filename);
         if (stats.isDirectory()) {
           filename += '/index.html';
         }
 
-        fs.readFile(filename, 'binary', (err, file) => {
-          if (err) {
-            response.writeHead(404, { 'Content-Type': 'text/plain' });
-            response.end();
-            return;
-          }
+        const file = await fs.readFile(filename, 'binary');
+        const cspHeaders = [
+          ...(useCsp ? ['script-src \'self\' \'unsafe-inline\''] : [])
+        ];
+        response.writeHead(200, { 'Content-Security-Policy': cspHeaders });
+        response.write(file, 'binary');
+      } catch {
+        response.writeHead(404, { 'Content-Type': 'text/plain' });
+      }
 
-          const cspHeaders = [
-            ...(useCsp ? ['script-src \'self\' \'unsafe-inline\''] : [])
-          ];
-          response.writeHead(200, { 'Content-Security-Policy': cspHeaders });
-          response.write(file, 'binary');
-          response.end();
-        });
-      });
+      response.end();
     });
 
     serverUrl = `http://localhost2:${(await listen(server)).port}`;

+ 9 - 10
spec/spellchecker-spec.ts

@@ -2,7 +2,7 @@ import { BrowserWindow, Session, session } from 'electron/main';
 
 import { expect } from 'chai';
 import * as path from 'node:path';
-import * as fs from 'node:fs';
+import * as fs from 'node:fs/promises';
 import * as http from 'node:http';
 import { closeWindow } from './lib/window-helpers';
 import { ifit, ifdescribe, listen } from './lib/spec-helpers';
@@ -43,19 +43,18 @@ ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', function ()
   }
 
   // Setup a server to download hunspell dictionary.
-  const server = http.createServer((req, res) => {
+  const server = http.createServer(async (req, res) => {
     // The provided is minimal dict for testing only, full list of words can
     // be found at src/third_party/hunspell_dictionaries/xx_XX.dic.
-    fs.readFile(path.join(__dirname, '/../../third_party/hunspell_dictionaries/xx-XX-3-0.bdic'), function (err, data) {
-      if (err) {
-        console.error('Failed to read dictionary file');
-        res.writeHead(404);
-        res.end(JSON.stringify(err));
-        return;
-      }
+    try {
+      const data = await fs.readFile(path.join(__dirname, '/../../third_party/hunspell_dictionaries/xx-XX-3-0.bdic'));
       res.writeHead(200);
       res.end(data);
-    });
+    } catch (err) {
+      console.error('Failed to read dictionary file');
+      res.writeHead(404);
+      res.end(JSON.stringify(err));
+    }
   });
   let serverUrl: string;
   before(async () => {