api-app-spec.ts 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. import { expect } from 'chai';
  2. import * as cp from 'child_process';
  3. import * as https from 'https';
  4. import * as http from 'http';
  5. import * as net from 'net';
  6. import * as fs from 'fs';
  7. import * as path from 'path';
  8. import { app, BrowserWindow, Menu, session } from 'electron';
  9. import { emittedOnce } from './events-helpers';
  10. import { closeWindow, closeAllWindows } from './window-helpers';
  11. import { ifdescribe, ifit } from './spec-helpers';
  12. import split = require('split')
  13. const features = process.electronBinding('features');
  14. const fixturesPath = path.resolve(__dirname, '../spec/fixtures');
  15. describe('electron module', () => {
  16. it('does not expose internal modules to require', () => {
  17. expect(() => {
  18. require('clipboard');
  19. }).to.throw(/Cannot find module 'clipboard'/);
  20. });
  21. describe('require("electron")', () => {
  22. it('always returns the internal electron module', () => {
  23. require('electron');
  24. });
  25. });
  26. });
  27. describe('app module', () => {
  28. let server: https.Server;
  29. let secureUrl: string;
  30. const certPath = path.join(fixturesPath, 'certificates');
  31. before((done) => {
  32. const options = {
  33. key: fs.readFileSync(path.join(certPath, 'server.key')),
  34. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  35. ca: [
  36. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  37. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  38. ],
  39. requestCert: true,
  40. rejectUnauthorized: false
  41. };
  42. server = https.createServer(options, (req, res) => {
  43. if ((req as any).client.authorized) {
  44. res.writeHead(200);
  45. res.end('<title>authorized</title>');
  46. } else {
  47. res.writeHead(401);
  48. res.end('<title>denied</title>');
  49. }
  50. });
  51. server.listen(0, '127.0.0.1', () => {
  52. const port = (server.address() as net.AddressInfo).port;
  53. secureUrl = `https://127.0.0.1:${port}`;
  54. done();
  55. });
  56. });
  57. after(done => {
  58. server.close(() => done());
  59. });
  60. describe('app.getVersion()', () => {
  61. it('returns the version field of package.json', () => {
  62. expect(app.getVersion()).to.equal('0.1.0');
  63. });
  64. });
  65. describe('app.setVersion(version)', () => {
  66. it('overrides the version', () => {
  67. expect(app.getVersion()).to.equal('0.1.0');
  68. app.setVersion('test-version');
  69. expect(app.getVersion()).to.equal('test-version');
  70. app.setVersion('0.1.0');
  71. });
  72. });
  73. describe('app name APIs', () => {
  74. it('with properties', () => {
  75. it('returns the name field of package.json', () => {
  76. expect(app.name).to.equal('Electron Test Main');
  77. });
  78. it('overrides the name', () => {
  79. expect(app.name).to.equal('Electron Test Main');
  80. app.name = 'test-name';
  81. expect(app.name).to.equal('test-name');
  82. app.name = 'Electron Test Main';
  83. });
  84. });
  85. it('with functions', () => {
  86. it('returns the name field of package.json', () => {
  87. expect(app.getName()).to.equal('Electron Test Main');
  88. });
  89. it('overrides the name', () => {
  90. expect(app.getName()).to.equal('Electron Test Main');
  91. app.setName('test-name');
  92. expect(app.getName()).to.equal('test-name');
  93. app.setName('Electron Test Main');
  94. });
  95. });
  96. });
  97. describe('app.getLocale()', () => {
  98. it('should not be empty', () => {
  99. expect(app.getLocale()).to.not.equal('');
  100. });
  101. });
  102. describe('app.getLocaleCountryCode()', () => {
  103. it('should be empty or have length of two', () => {
  104. let expectedLength = 2;
  105. if (process.platform === 'linux') {
  106. // Linux CI machines have no locale.
  107. expectedLength = 0;
  108. }
  109. expect(app.getLocaleCountryCode()).to.be.a('string').and.have.lengthOf(expectedLength);
  110. });
  111. });
  112. describe('app.isPackaged', () => {
  113. it('should be false durings tests', () => {
  114. expect(app.isPackaged).to.equal(false);
  115. });
  116. });
  117. ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
  118. it('should be false during tests', () => {
  119. expect(app.isInApplicationsFolder()).to.equal(false);
  120. });
  121. });
  122. describe('app.exit(exitCode)', () => {
  123. let appProcess: cp.ChildProcess | null = null;
  124. afterEach(() => {
  125. if (appProcess) appProcess.kill();
  126. });
  127. it('emits a process exit event with the code', async () => {
  128. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  129. const electronPath = process.execPath;
  130. let output = '';
  131. appProcess = cp.spawn(electronPath, [appPath]);
  132. if (appProcess && appProcess.stdout) {
  133. appProcess.stdout.on('data', data => { output += data; });
  134. }
  135. const [code] = await emittedOnce(appProcess, 'exit');
  136. if (process.platform !== 'win32') {
  137. expect(output).to.include('Exit event with code: 123');
  138. }
  139. expect(code).to.equal(123);
  140. });
  141. it('closes all windows', async function () {
  142. const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
  143. const electronPath = process.execPath;
  144. appProcess = cp.spawn(electronPath, [appPath]);
  145. const [code, signal] = await emittedOnce(appProcess, 'exit');
  146. expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
  147. expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
  148. });
  149. it('exits gracefully', async function () {
  150. if (!['darwin', 'linux'].includes(process.platform)) {
  151. this.skip();
  152. return;
  153. }
  154. const electronPath = process.execPath;
  155. const appPath = path.join(fixturesPath, 'api', 'singleton');
  156. appProcess = cp.spawn(electronPath, [appPath]);
  157. // Singleton will send us greeting data to let us know it's running.
  158. // After that, ask it to exit gracefully and confirm that it does.
  159. if (appProcess && appProcess.stdout) {
  160. appProcess.stdout.on('data', () => appProcess!.kill());
  161. }
  162. const [code, signal] = await emittedOnce(appProcess, 'exit');
  163. const message = `code:\n${code}\nsignal:\n${signal}`;
  164. expect(code).to.equal(0, message);
  165. expect(signal).to.equal(null, message);
  166. });
  167. });
  168. ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
  169. it('throws an error on invalid application policies', () => {
  170. expect(() => {
  171. app.setActivationPolicy('terrible' as any);
  172. }).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
  173. });
  174. });
  175. describe('app.requestSingleInstanceLock', () => {
  176. it('prevents the second launch of app', function (done) {
  177. this.timeout(120000);
  178. const appPath = path.join(fixturesPath, 'api', 'singleton');
  179. const first = cp.spawn(process.execPath, [appPath]);
  180. first.once('exit', code => {
  181. expect(code).to.equal(0);
  182. });
  183. // Start second app when received output.
  184. first.stdout.once('data', () => {
  185. const second = cp.spawn(process.execPath, [appPath]);
  186. second.once('exit', code => {
  187. expect(code).to.equal(1);
  188. done();
  189. });
  190. });
  191. });
  192. it('passes arguments to the second-instance event', async () => {
  193. const appPath = path.join(fixturesPath, 'api', 'singleton');
  194. const first = cp.spawn(process.execPath, [appPath]);
  195. const firstExited = emittedOnce(first, 'exit');
  196. // Wait for the first app to boot.
  197. const firstStdoutLines = first.stdout.pipe(split());
  198. while ((await emittedOnce(firstStdoutLines, 'data')).toString() !== 'started') {
  199. // wait.
  200. }
  201. const data2Promise = emittedOnce(firstStdoutLines, 'data');
  202. const secondInstanceArgs = [process.execPath, appPath, '--some-switch', 'some-arg'];
  203. const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
  204. const [code2] = await emittedOnce(second, 'exit');
  205. expect(code2).to.equal(1);
  206. const [code1] = await firstExited;
  207. expect(code1).to.equal(0);
  208. const data2 = (await data2Promise)[0].toString('ascii');
  209. const secondInstanceArgsReceived: string[] = JSON.parse(data2.toString('ascii'));
  210. const expected = process.platform === 'win32'
  211. ? [process.execPath, '--some-switch', '--allow-file-access-from-files', appPath, 'some-arg']
  212. : secondInstanceArgs;
  213. expect(secondInstanceArgsReceived).to.eql(expected,
  214. `expected ${JSON.stringify(expected)} but got ${data2.toString('ascii')}`);
  215. });
  216. });
  217. describe('app.relaunch', () => {
  218. let server: net.Server | null = null;
  219. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
  220. beforeEach(done => {
  221. fs.unlink(socketPath, () => {
  222. server = net.createServer();
  223. server.listen(socketPath);
  224. done();
  225. });
  226. });
  227. afterEach((done) => {
  228. server!.close(() => {
  229. if (process.platform === 'win32') {
  230. done();
  231. } else {
  232. fs.unlink(socketPath, () => done());
  233. }
  234. });
  235. });
  236. it('relaunches the app', function (done) {
  237. this.timeout(120000);
  238. let state = 'none';
  239. server!.once('error', error => done(error));
  240. server!.on('connection', client => {
  241. client.once('data', data => {
  242. if (String(data) === 'false' && state === 'none') {
  243. state = 'first-launch';
  244. } else if (String(data) === 'true' && state === 'first-launch') {
  245. done();
  246. } else {
  247. done(`Unexpected state: ${state}`);
  248. }
  249. });
  250. });
  251. const appPath = path.join(fixturesPath, 'api', 'relaunch');
  252. cp.spawn(process.execPath, [appPath]);
  253. });
  254. });
  255. describe('app.setUserActivity(type, userInfo)', () => {
  256. before(function () {
  257. if (process.platform !== 'darwin') {
  258. this.skip();
  259. }
  260. });
  261. it('sets the current activity', () => {
  262. app.setUserActivity('com.electron.testActivity', { testData: '123' });
  263. expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
  264. });
  265. });
  266. describe('certificate-error event', () => {
  267. afterEach(closeAllWindows);
  268. it('is emitted when visiting a server with a self-signed cert', async () => {
  269. const w = new BrowserWindow({ show: false });
  270. w.loadURL(secureUrl);
  271. await emittedOnce(app, 'certificate-error');
  272. });
  273. });
  274. // xdescribe('app.importCertificate', () => {
  275. // let w = null
  276. // before(function () {
  277. // if (process.platform !== 'linux') {
  278. // this.skip()
  279. // }
  280. // })
  281. // afterEach(() => closeWindow(w).then(() => { w = null }))
  282. // it('can import certificate into platform cert store', done => {
  283. // const options = {
  284. // certificate: path.join(certPath, 'client.p12'),
  285. // password: 'electron'
  286. // }
  287. // w = new BrowserWindow({
  288. // show: false,
  289. // webPreferences: {
  290. // nodeIntegration: true
  291. // }
  292. // })
  293. // w.webContents.on('did-finish-load', () => {
  294. // expect(w.webContents.getTitle()).to.equal('authorized')
  295. // done()
  296. // })
  297. // ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
  298. // expect(webContentsId).to.equal(w.webContents.id)
  299. // expect(list).to.have.lengthOf(1)
  300. // expect(list[0]).to.deep.equal({
  301. // issuerName: 'Intermediate CA',
  302. // subjectName: 'Client Cert',
  303. // issuer: { commonName: 'Intermediate CA' },
  304. // subject: { commonName: 'Client Cert' }
  305. // })
  306. // event.sender.send('client-certificate-response', list[0])
  307. // })
  308. // app.importCertificate(options, result => {
  309. // expect(result).toNotExist()
  310. // ipcRenderer.sendSync('set-client-certificate-option', false)
  311. // w.loadURL(secureUrl)
  312. // })
  313. // })
  314. // })
  315. describe('BrowserWindow events', () => {
  316. let w: BrowserWindow = null as any;
  317. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  318. it('should emit browser-window-focus event when window is focused', async () => {
  319. const emitted = emittedOnce(app, 'browser-window-focus');
  320. w = new BrowserWindow({ show: false });
  321. w.emit('focus');
  322. const [, window] = await emitted;
  323. expect(window.id).to.equal(w.id);
  324. });
  325. it('should emit browser-window-blur event when window is blured', async () => {
  326. const emitted = emittedOnce(app, 'browser-window-blur');
  327. w = new BrowserWindow({ show: false });
  328. w.emit('blur');
  329. const [, window] = await emitted;
  330. expect(window.id).to.equal(w.id);
  331. });
  332. it('should emit browser-window-created event when window is created', async () => {
  333. const emitted = emittedOnce(app, 'browser-window-created');
  334. w = new BrowserWindow({ show: false });
  335. const [, window] = await emitted;
  336. expect(window.id).to.equal(w.id);
  337. });
  338. it('should emit web-contents-created event when a webContents is created', async () => {
  339. const emitted = emittedOnce(app, 'web-contents-created');
  340. w = new BrowserWindow({ show: false });
  341. const [, webContents] = await emitted;
  342. expect(webContents.id).to.equal(w.webContents.id);
  343. });
  344. // FIXME: re-enable this test on win32.
  345. ifit(process.platform !== 'win32')('should emit renderer-process-crashed event when renderer crashes', async () => {
  346. w = new BrowserWindow({
  347. show: false,
  348. webPreferences: {
  349. nodeIntegration: true
  350. }
  351. });
  352. await w.loadURL('about:blank');
  353. const emitted = emittedOnce(app, 'renderer-process-crashed');
  354. w.webContents.executeJavaScript('process.crash()');
  355. const [, webContents] = await emitted;
  356. expect(webContents).to.equal(w.webContents);
  357. });
  358. it('should emit render-process-gone event when renderer crashes', async function () {
  359. // FIXME: re-enable this test on win32.
  360. if (process.platform === 'win32') { return this.skip(); }
  361. w = new BrowserWindow({
  362. show: false,
  363. webPreferences: {
  364. nodeIntegration: true
  365. }
  366. });
  367. await w.loadURL('about:blank');
  368. const promise = emittedOnce(app, 'render-process-gone');
  369. w.webContents.executeJavaScript('process.crash()');
  370. const [, webContents, details] = await promise;
  371. expect(webContents).to.equal(w.webContents);
  372. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  373. });
  374. ifdescribe(features.isDesktopCapturerEnabled())('desktopCapturer module filtering', () => {
  375. it('should emit desktop-capturer-get-sources event when desktopCapturer.getSources() is invoked', async () => {
  376. w = new BrowserWindow({
  377. show: false,
  378. webPreferences: {
  379. nodeIntegration: true
  380. }
  381. });
  382. await w.loadURL('about:blank');
  383. const promise = emittedOnce(app, 'desktop-capturer-get-sources');
  384. w.webContents.executeJavaScript('require(\'electron\').desktopCapturer.getSources({ types: [\'screen\'] })');
  385. const [, webContents] = await promise;
  386. expect(webContents).to.equal(w.webContents);
  387. });
  388. });
  389. ifdescribe(features.isRemoteModuleEnabled())('remote module filtering', () => {
  390. it('should emit remote-require event when remote.require() is invoked', async () => {
  391. w = new BrowserWindow({
  392. show: false,
  393. webPreferences: {
  394. nodeIntegration: true
  395. }
  396. });
  397. await w.loadURL('about:blank');
  398. const promise = emittedOnce(app, 'remote-require');
  399. w.webContents.executeJavaScript('require(\'electron\').remote.require(\'test\')');
  400. const [, webContents, moduleName] = await promise;
  401. expect(webContents).to.equal(w.webContents);
  402. expect(moduleName).to.equal('test');
  403. });
  404. it('should emit remote-get-global event when remote.getGlobal() is invoked', async () => {
  405. w = new BrowserWindow({
  406. show: false,
  407. webPreferences: {
  408. nodeIntegration: true
  409. }
  410. });
  411. await w.loadURL('about:blank');
  412. const promise = emittedOnce(app, 'remote-get-global');
  413. w.webContents.executeJavaScript('require(\'electron\').remote.getGlobal(\'test\')');
  414. const [, webContents, globalName] = await promise;
  415. expect(webContents).to.equal(w.webContents);
  416. expect(globalName).to.equal('test');
  417. });
  418. it('should emit remote-get-builtin event when remote.getBuiltin() is invoked', async () => {
  419. w = new BrowserWindow({
  420. show: false,
  421. webPreferences: {
  422. nodeIntegration: true
  423. }
  424. });
  425. await w.loadURL('about:blank');
  426. const promise = emittedOnce(app, 'remote-get-builtin');
  427. w.webContents.executeJavaScript('require(\'electron\').remote.app');
  428. const [, webContents, moduleName] = await promise;
  429. expect(webContents).to.equal(w.webContents);
  430. expect(moduleName).to.equal('app');
  431. });
  432. it('should emit remote-get-current-window event when remote.getCurrentWindow() is invoked', async () => {
  433. w = new BrowserWindow({
  434. show: false,
  435. webPreferences: {
  436. nodeIntegration: true
  437. }
  438. });
  439. await w.loadURL('about:blank');
  440. const promise = emittedOnce(app, 'remote-get-current-window');
  441. w.webContents.executeJavaScript('{ require(\'electron\').remote.getCurrentWindow() }');
  442. const [, webContents] = await promise;
  443. expect(webContents).to.equal(w.webContents);
  444. });
  445. it('should emit remote-get-current-web-contents event when remote.getCurrentWebContents() is invoked', async () => {
  446. w = new BrowserWindow({
  447. show: false,
  448. webPreferences: {
  449. nodeIntegration: true
  450. }
  451. });
  452. await w.loadURL('about:blank');
  453. const promise = emittedOnce(app, 'remote-get-current-web-contents');
  454. w.webContents.executeJavaScript('{ require(\'electron\').remote.getCurrentWebContents() }');
  455. const [, webContents] = await promise;
  456. expect(webContents).to.equal(w.webContents);
  457. });
  458. });
  459. });
  460. describe('app.badgeCount', () => {
  461. const platformIsNotSupported =
  462. (process.platform === 'win32') ||
  463. (process.platform === 'linux' && !app.isUnityRunning());
  464. const platformIsSupported = !platformIsNotSupported;
  465. const expectedBadgeCount = 42;
  466. after(() => { app.badgeCount = 0; });
  467. describe('on supported platform', () => {
  468. it('with properties', () => {
  469. it('sets a badge count', function () {
  470. if (platformIsNotSupported) return this.skip();
  471. app.badgeCount = expectedBadgeCount;
  472. expect(app.badgeCount).to.equal(expectedBadgeCount);
  473. });
  474. });
  475. it('with functions', () => {
  476. it('sets a badge count', function () {
  477. if (platformIsNotSupported) return this.skip();
  478. app.setBadgeCount(expectedBadgeCount);
  479. expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
  480. });
  481. });
  482. });
  483. describe('on unsupported platform', () => {
  484. it('with properties', () => {
  485. it('does not set a badge count', function () {
  486. if (platformIsSupported) return this.skip();
  487. app.badgeCount = 9999;
  488. expect(app.badgeCount).to.equal(0);
  489. });
  490. });
  491. it('with functions', () => {
  492. it('does not set a badge count)', function () {
  493. if (platformIsSupported) return this.skip();
  494. app.setBadgeCount(9999);
  495. expect(app.getBadgeCount()).to.equal(0);
  496. });
  497. });
  498. });
  499. });
  500. describe('app.get/setLoginItemSettings API', function () {
  501. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  502. const processStartArgs = [
  503. '--processStart', `"${path.basename(process.execPath)}"`,
  504. '--process-start-args', '"--hidden"'
  505. ];
  506. before(function () {
  507. if (process.platform === 'linux' || process.mas) this.skip();
  508. });
  509. beforeEach(() => {
  510. app.setLoginItemSettings({ openAtLogin: false });
  511. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  512. });
  513. afterEach(() => {
  514. app.setLoginItemSettings({ openAtLogin: false });
  515. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  516. });
  517. it('sets and returns the app as a login item', done => {
  518. app.setLoginItemSettings({ openAtLogin: true });
  519. expect(app.getLoginItemSettings()).to.deep.equal({
  520. openAtLogin: true,
  521. openAsHidden: false,
  522. wasOpenedAtLogin: false,
  523. wasOpenedAsHidden: false,
  524. restoreState: false
  525. });
  526. done();
  527. });
  528. it('adds a login item that loads in hidden mode', done => {
  529. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  530. expect(app.getLoginItemSettings()).to.deep.equal({
  531. openAtLogin: true,
  532. openAsHidden: process.platform === 'darwin' && !process.mas, // Only available on macOS
  533. wasOpenedAtLogin: false,
  534. wasOpenedAsHidden: false,
  535. restoreState: false
  536. });
  537. done();
  538. });
  539. it('correctly sets and unsets the LoginItem', function () {
  540. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  541. app.setLoginItemSettings({ openAtLogin: true });
  542. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  543. app.setLoginItemSettings({ openAtLogin: false });
  544. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  545. });
  546. it('correctly sets and unsets the LoginItem as hidden', function () {
  547. if (process.platform !== 'darwin') this.skip();
  548. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  549. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  550. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  551. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  552. expect(app.getLoginItemSettings().openAsHidden).to.equal(true);
  553. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
  554. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  555. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  556. });
  557. it('allows you to pass a custom executable and arguments', function () {
  558. if (process.platform !== 'win32') this.skip();
  559. app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs });
  560. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  561. expect(app.getLoginItemSettings({
  562. path: updateExe,
  563. args: processStartArgs
  564. }).openAtLogin).to.equal(true);
  565. });
  566. });
  567. ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
  568. it('with properties', () => {
  569. it('can set accessibility support enabled', () => {
  570. expect(app.accessibilitySupportEnabled).to.eql(false);
  571. app.accessibilitySupportEnabled = true;
  572. expect(app.accessibilitySupportEnabled).to.eql(true);
  573. });
  574. });
  575. it('with functions', () => {
  576. it('can set accessibility support enabled', () => {
  577. expect(app.isAccessibilitySupportEnabled()).to.eql(false);
  578. app.setAccessibilitySupportEnabled(true);
  579. expect(app.isAccessibilitySupportEnabled()).to.eql(true);
  580. });
  581. });
  582. });
  583. describe('getAppPath', () => {
  584. it('works for directories with package.json', async () => {
  585. const { appPath } = await runTestApp('app-path');
  586. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
  587. });
  588. it('works for directories with index.js', async () => {
  589. const { appPath } = await runTestApp('app-path/lib');
  590. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  591. });
  592. it('works for files without extension', async () => {
  593. const { appPath } = await runTestApp('app-path/lib/index');
  594. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  595. });
  596. it('works for files', async () => {
  597. const { appPath } = await runTestApp('app-path/lib/index.js');
  598. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  599. });
  600. });
  601. describe('getPath(name)', () => {
  602. it('returns paths that exist', () => {
  603. const paths = [
  604. fs.existsSync(app.getPath('exe')),
  605. fs.existsSync(app.getPath('home')),
  606. fs.existsSync(app.getPath('temp'))
  607. ];
  608. expect(paths).to.deep.equal([true, true, true]);
  609. });
  610. it('throws an error when the name is invalid', () => {
  611. expect(() => {
  612. app.getPath('does-not-exist' as any);
  613. }).to.throw(/Failed to get 'does-not-exist' path/);
  614. });
  615. it('returns the overridden path', () => {
  616. app.setPath('music', __dirname);
  617. expect(app.getPath('music')).to.equal(__dirname);
  618. });
  619. });
  620. describe('setPath(name, path)', () => {
  621. it('throws when a relative path is passed', () => {
  622. const badPath = 'hey/hi/hello';
  623. expect(() => {
  624. app.setPath('music', badPath);
  625. }).to.throw(/Path must be absolute/);
  626. });
  627. it('does not create a new directory by default', () => {
  628. const badPath = path.join(__dirname, 'music');
  629. expect(fs.existsSync(badPath)).to.be.false();
  630. app.setPath('music', badPath);
  631. expect(fs.existsSync(badPath)).to.be.false();
  632. expect(() => { app.getPath(badPath as any); }).to.throw();
  633. });
  634. });
  635. describe('setAppLogsPath(path)', () => {
  636. it('throws when a relative path is passed', () => {
  637. const badPath = 'hey/hi/hello';
  638. expect(() => {
  639. app.setAppLogsPath(badPath);
  640. }).to.throw(/Path must be absolute/);
  641. });
  642. });
  643. describe('select-client-certificate event', () => {
  644. let w: BrowserWindow;
  645. before(function () {
  646. if (process.platform === 'linux') {
  647. this.skip();
  648. }
  649. session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
  650. });
  651. beforeEach(() => {
  652. w = new BrowserWindow({
  653. show: false,
  654. webPreferences: {
  655. nodeIntegration: true,
  656. partition: 'empty-certificate'
  657. }
  658. });
  659. });
  660. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  661. after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
  662. it('can respond with empty certificate list', async () => {
  663. app.once('select-client-certificate', function (event, webContents, url, list, callback) {
  664. console.log('select-client-certificate emitted');
  665. event.preventDefault();
  666. callback();
  667. });
  668. await w.webContents.loadURL(secureUrl);
  669. expect(w.webContents.getTitle()).to.equal('denied');
  670. });
  671. });
  672. describe('setAsDefaultProtocolClient(protocol, path, args)', () => {
  673. const protocol = 'electron-test';
  674. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  675. const processStartArgs = [
  676. '--processStart', `"${path.basename(process.execPath)}"`,
  677. '--process-start-args', '"--hidden"'
  678. ];
  679. let Winreg: any;
  680. let classesKey: any;
  681. before(function () {
  682. if (process.platform !== 'win32') {
  683. this.skip();
  684. } else {
  685. Winreg = require('winreg');
  686. classesKey = new Winreg({
  687. hive: Winreg.HKCU,
  688. key: '\\Software\\Classes\\'
  689. });
  690. }
  691. });
  692. after(function (done) {
  693. if (process.platform !== 'win32') {
  694. done();
  695. } else {
  696. const protocolKey = new Winreg({
  697. hive: Winreg.HKCU,
  698. key: `\\Software\\Classes\\${protocol}`
  699. });
  700. // The last test leaves the registry dirty,
  701. // delete the protocol key for those of us who test at home
  702. protocolKey.destroy(() => done());
  703. }
  704. });
  705. beforeEach(() => {
  706. app.removeAsDefaultProtocolClient(protocol);
  707. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  708. });
  709. afterEach(() => {
  710. app.removeAsDefaultProtocolClient(protocol);
  711. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  712. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  713. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  714. });
  715. it('sets the app as the default protocol client', () => {
  716. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  717. app.setAsDefaultProtocolClient(protocol);
  718. expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
  719. });
  720. it('allows a custom path and args to be specified', () => {
  721. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  722. app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  723. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
  724. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  725. });
  726. it('creates a registry entry for the protocol class', (done) => {
  727. app.setAsDefaultProtocolClient(protocol);
  728. classesKey.keys((error: Error, keys: any[]) => {
  729. if (error) throw error;
  730. const exists = !!keys.find(key => key.key.includes(protocol));
  731. expect(exists).to.equal(true);
  732. done();
  733. });
  734. });
  735. it('completely removes a registry entry for the protocol class', (done) => {
  736. app.setAsDefaultProtocolClient(protocol);
  737. app.removeAsDefaultProtocolClient(protocol);
  738. classesKey.keys((error: Error, keys: any[]) => {
  739. if (error) throw error;
  740. const exists = !!keys.find(key => key.key.includes(protocol));
  741. expect(exists).to.equal(false);
  742. done();
  743. });
  744. });
  745. it('only unsets a class registry key if it contains other data', (done) => {
  746. app.setAsDefaultProtocolClient(protocol);
  747. const protocolKey = new Winreg({
  748. hive: Winreg.HKCU,
  749. key: `\\Software\\Classes\\${protocol}`
  750. });
  751. protocolKey.set('test-value', 'REG_BINARY', '123', () => {
  752. app.removeAsDefaultProtocolClient(protocol);
  753. classesKey.keys((error: Error, keys: any[]) => {
  754. if (error) throw error;
  755. const exists = !!keys.find(key => key.key.includes(protocol));
  756. expect(exists).to.equal(true);
  757. done();
  758. });
  759. });
  760. });
  761. it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
  762. app.setAsDefaultProtocolClient(protocol);
  763. expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
  764. });
  765. });
  766. describe('getApplicationNameForProtocol()', () => {
  767. it('returns application names for common protocols', function () {
  768. // We can't expect particular app names here, but these protocols should
  769. // at least have _something_ registered. Except on our Linux CI
  770. // environment apparently.
  771. if (process.platform === 'linux') {
  772. this.skip();
  773. }
  774. const protocols = [
  775. 'http://',
  776. 'https://'
  777. ];
  778. protocols.forEach((protocol) => {
  779. expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
  780. });
  781. });
  782. it('returns an empty string for a bogus protocol', () => {
  783. expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
  784. });
  785. });
  786. describe('isDefaultProtocolClient()', () => {
  787. it('returns false for a bogus protocol', () => {
  788. expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
  789. });
  790. });
  791. describe('app launch through uri', () => {
  792. before(function () {
  793. if (process.platform !== 'win32') {
  794. this.skip();
  795. }
  796. });
  797. it('does not launch for argument following a URL', done => {
  798. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  799. // App should exit with non 123 code.
  800. const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
  801. first.once('exit', code => {
  802. expect(code).to.not.equal(123);
  803. done();
  804. });
  805. });
  806. it('launches successfully for argument following a file path', done => {
  807. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  808. // App should exit with code 123.
  809. const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
  810. first.once('exit', code => {
  811. expect(code).to.equal(123);
  812. done();
  813. });
  814. });
  815. it('launches successfully for multiple URIs following --', done => {
  816. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  817. // App should exit with code 123.
  818. const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
  819. first.once('exit', code => {
  820. expect(code).to.equal(123);
  821. done();
  822. });
  823. });
  824. });
  825. // FIXME Get these specs running on Linux CI
  826. ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
  827. const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
  828. const sizes = {
  829. small: 16,
  830. normal: 32,
  831. large: process.platform === 'win32' ? 32 : 48
  832. };
  833. it('fetches a non-empty icon', async () => {
  834. const icon = await app.getFileIcon(iconPath);
  835. expect(icon.isEmpty()).to.equal(false);
  836. });
  837. it('fetches normal icon size by default', async () => {
  838. const icon = await app.getFileIcon(iconPath);
  839. const size = icon.getSize();
  840. expect(size.height).to.equal(sizes.normal);
  841. expect(size.width).to.equal(sizes.normal);
  842. });
  843. describe('size option', () => {
  844. it('fetches a small icon', async () => {
  845. const icon = await app.getFileIcon(iconPath, { size: 'small' });
  846. const size = icon.getSize();
  847. expect(size.height).to.equal(sizes.small);
  848. expect(size.width).to.equal(sizes.small);
  849. });
  850. it('fetches a normal icon', async () => {
  851. const icon = await app.getFileIcon(iconPath, { size: 'normal' });
  852. const size = icon.getSize();
  853. expect(size.height).to.equal(sizes.normal);
  854. expect(size.width).to.equal(sizes.normal);
  855. });
  856. it('fetches a large icon', async () => {
  857. // macOS does not support large icons
  858. if (process.platform === 'darwin') return;
  859. const icon = await app.getFileIcon(iconPath, { size: 'large' });
  860. const size = icon.getSize();
  861. expect(size.height).to.equal(sizes.large);
  862. expect(size.width).to.equal(sizes.large);
  863. });
  864. });
  865. });
  866. describe('getAppMetrics() API', () => {
  867. it('returns memory and cpu stats of all running electron processes', () => {
  868. const appMetrics = app.getAppMetrics();
  869. expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
  870. const types = [];
  871. for (const entry of appMetrics) {
  872. expect(entry.pid).to.be.above(0, 'pid is not > 0');
  873. expect(entry.type).to.be.a('string').that.does.not.equal('');
  874. expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
  875. types.push(entry.type);
  876. expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
  877. expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
  878. expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
  879. expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
  880. if (process.platform === 'win32') {
  881. expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
  882. }
  883. if (process.platform !== 'linux') {
  884. expect(entry.sandboxed).to.be.a('boolean');
  885. }
  886. if (process.platform === 'win32') {
  887. expect(entry.integrityLevel).to.be.a('string');
  888. }
  889. }
  890. if (process.platform === 'darwin') {
  891. expect(types).to.include('GPU');
  892. }
  893. expect(types).to.include('Browser');
  894. });
  895. });
  896. describe('getGPUFeatureStatus() API', () => {
  897. it('returns the graphic features statuses', () => {
  898. const features = app.getGPUFeatureStatus();
  899. expect(features).to.have.ownProperty('webgl').that.is.a('string');
  900. expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
  901. });
  902. });
  903. describe('getGPUInfo() API', () => {
  904. const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
  905. const getGPUInfo = async (type: string) => {
  906. const appProcess = cp.spawn(process.execPath, [appPath, type]);
  907. let gpuInfoData = '';
  908. let errorData = '';
  909. appProcess.stdout.on('data', (data) => {
  910. gpuInfoData += data;
  911. });
  912. appProcess.stderr.on('data', (data) => {
  913. errorData += data;
  914. });
  915. const [exitCode] = await emittedOnce(appProcess, 'exit');
  916. if (exitCode === 0) {
  917. // return info data on successful exit
  918. return JSON.parse(gpuInfoData);
  919. } else {
  920. // return error if not clean exit
  921. return Promise.reject(new Error(errorData));
  922. }
  923. };
  924. const verifyBasicGPUInfo = async (gpuInfo: any) => {
  925. // Devices information is always present in the available info.
  926. expect(gpuInfo).to.have.ownProperty('gpuDevice')
  927. .that.is.an('array')
  928. .and.does.not.equal([]);
  929. const device = gpuInfo.gpuDevice[0];
  930. expect(device).to.be.an('object')
  931. .and.to.have.property('deviceId')
  932. .that.is.a('number')
  933. .not.lessThan(0);
  934. };
  935. it('succeeds with basic GPUInfo', async () => {
  936. const gpuInfo = await getGPUInfo('basic');
  937. await verifyBasicGPUInfo(gpuInfo);
  938. });
  939. it('succeeds with complete GPUInfo', async () => {
  940. const completeInfo = await getGPUInfo('complete');
  941. if (process.platform === 'linux') {
  942. // For linux and macOS complete info is same as basic info
  943. await verifyBasicGPUInfo(completeInfo);
  944. const basicInfo = await getGPUInfo('basic');
  945. expect(completeInfo).to.deep.equal(basicInfo);
  946. } else {
  947. // Gl version is present in the complete info.
  948. expect(completeInfo).to.have.ownProperty('auxAttributes')
  949. .that.is.an('object');
  950. if (completeInfo.gpuDevice.active) {
  951. expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
  952. .that.is.a('string')
  953. .and.does.not.equal([]);
  954. }
  955. }
  956. });
  957. it('fails for invalid info_type', () => {
  958. const invalidType = 'invalid';
  959. const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
  960. return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
  961. });
  962. });
  963. describe('sandbox options', () => {
  964. let appProcess: cp.ChildProcess = null as any;
  965. let server: net.Server = null as any;
  966. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
  967. beforeEach(function (done) {
  968. if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')) {
  969. // Our ARM tests are run on VSTS rather than CircleCI, and the Docker
  970. // setup on VSTS disallows syscalls that Chrome requires for setting up
  971. // sandboxing.
  972. // See:
  973. // - https://docs.docker.com/engine/security/seccomp/#significant-syscalls-blocked-by-the-default-profile
  974. // - https://chromium.googlesource.com/chromium/src/+/70.0.3538.124/sandbox/linux/services/credentials.cc#292
  975. // - https://github.com/docker/docker-ce/blob/ba7dfc59ccfe97c79ee0d1379894b35417b40bca/components/engine/profiles/seccomp/seccomp_default.go#L497
  976. // - https://blog.jessfraz.com/post/how-to-use-new-docker-seccomp-profiles/
  977. //
  978. // Adding `--cap-add SYS_ADMIN` or `--security-opt seccomp=unconfined`
  979. // to the Docker invocation allows the syscalls that Chrome needs, but
  980. // are probably more permissive than we'd like.
  981. this.skip();
  982. }
  983. fs.unlink(socketPath, () => {
  984. server = net.createServer();
  985. server.listen(socketPath);
  986. done();
  987. });
  988. });
  989. afterEach(done => {
  990. if (appProcess != null) appProcess.kill();
  991. server.close(() => {
  992. if (process.platform === 'win32') {
  993. done();
  994. } else {
  995. fs.unlink(socketPath, () => done());
  996. }
  997. });
  998. });
  999. describe('when app.enableSandbox() is called', () => {
  1000. it('adds --enable-sandbox to all renderer processes', done => {
  1001. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1002. appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox']);
  1003. server.once('error', error => { done(error); });
  1004. server.on('connection', client => {
  1005. client.once('data', (data) => {
  1006. const argv = JSON.parse(data.toString());
  1007. expect(argv.sandbox).to.include('--enable-sandbox');
  1008. expect(argv.sandbox).to.not.include('--no-sandbox');
  1009. expect(argv.noSandbox).to.include('--enable-sandbox');
  1010. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1011. expect(argv.noSandboxDevtools).to.equal(true);
  1012. expect(argv.sandboxDevtools).to.equal(true);
  1013. done();
  1014. });
  1015. });
  1016. });
  1017. });
  1018. describe('when the app is launched with --enable-sandbox', () => {
  1019. it('adds --enable-sandbox to all renderer processes', done => {
  1020. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1021. appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox']);
  1022. server.once('error', error => { done(error); });
  1023. server.on('connection', client => {
  1024. client.once('data', data => {
  1025. const argv = JSON.parse(data.toString());
  1026. expect(argv.sandbox).to.include('--enable-sandbox');
  1027. expect(argv.sandbox).to.not.include('--no-sandbox');
  1028. expect(argv.noSandbox).to.include('--enable-sandbox');
  1029. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1030. expect(argv.noSandboxDevtools).to.equal(true);
  1031. expect(argv.sandboxDevtools).to.equal(true);
  1032. done();
  1033. });
  1034. });
  1035. });
  1036. });
  1037. });
  1038. describe('disableDomainBlockingFor3DAPIs() API', () => {
  1039. it('throws when called after app is ready', () => {
  1040. expect(() => {
  1041. app.disableDomainBlockingFor3DAPIs();
  1042. }).to.throw(/before app is ready/);
  1043. });
  1044. });
  1045. const dockDescribe = process.platform === 'darwin' ? describe : describe.skip;
  1046. dockDescribe('dock APIs', () => {
  1047. after(async () => {
  1048. await app.dock.show();
  1049. });
  1050. describe('dock.setMenu', () => {
  1051. it('can be retrieved via dock.getMenu', () => {
  1052. expect(app.dock.getMenu()).to.equal(null);
  1053. const menu = new Menu();
  1054. app.dock.setMenu(menu);
  1055. expect(app.dock.getMenu()).to.equal(menu);
  1056. });
  1057. it('keeps references to the menu', () => {
  1058. app.dock.setMenu(new Menu());
  1059. const v8Util = process.electronBinding('v8_util');
  1060. v8Util.requestGarbageCollectionForTesting();
  1061. });
  1062. });
  1063. describe('dock.bounce', () => {
  1064. it('should return -1 for unknown bounce type', () => {
  1065. expect(app.dock.bounce('bad type' as any)).to.equal(-1);
  1066. });
  1067. it('should return a positive number for informational type', () => {
  1068. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1069. if (!appHasFocus) {
  1070. expect(app.dock.bounce('informational')).to.be.at.least(0);
  1071. }
  1072. });
  1073. it('should return a positive number for critical type', () => {
  1074. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1075. if (!appHasFocus) {
  1076. expect(app.dock.bounce('critical')).to.be.at.least(0);
  1077. }
  1078. });
  1079. });
  1080. describe('dock.cancelBounce', () => {
  1081. it('should not throw', () => {
  1082. app.dock.cancelBounce(app.dock.bounce('critical'));
  1083. });
  1084. });
  1085. describe('dock.setBadge', () => {
  1086. after(() => {
  1087. app.dock.setBadge('');
  1088. });
  1089. it('should not throw', () => {
  1090. app.dock.setBadge('1');
  1091. });
  1092. it('should be retrievable via getBadge', () => {
  1093. app.dock.setBadge('test');
  1094. expect(app.dock.getBadge()).to.equal('test');
  1095. });
  1096. });
  1097. describe('dock.hide', () => {
  1098. it('should not throw', () => {
  1099. app.dock.hide();
  1100. expect(app.dock.isVisible()).to.equal(false);
  1101. });
  1102. });
  1103. // Note that dock.show tests should run after dock.hide tests, to work
  1104. // around a bug of macOS.
  1105. // See https://github.com/electron/electron/pull/25269 for more.
  1106. describe('dock.show', () => {
  1107. it('should not throw', () => {
  1108. return app.dock.show().then(() => {
  1109. expect(app.dock.isVisible()).to.equal(true);
  1110. });
  1111. });
  1112. it('returns a Promise', () => {
  1113. expect(app.dock.show()).to.be.a('promise');
  1114. });
  1115. it('eventually fulfills', async () => {
  1116. await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
  1117. });
  1118. });
  1119. });
  1120. describe('whenReady', () => {
  1121. it('returns a Promise', () => {
  1122. expect(app.whenReady()).to.be.a('promise');
  1123. });
  1124. it('becomes fulfilled if the app is already ready', async () => {
  1125. expect(app.isReady()).to.equal(true);
  1126. await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
  1127. });
  1128. });
  1129. describe('app.applicationMenu', () => {
  1130. it('has the applicationMenu property', () => {
  1131. expect(app).to.have.property('applicationMenu');
  1132. });
  1133. });
  1134. describe('commandLine.hasSwitch', () => {
  1135. it('returns true when present', () => {
  1136. app.commandLine.appendSwitch('foobar1');
  1137. expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
  1138. });
  1139. it('returns false when not present', () => {
  1140. expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
  1141. });
  1142. });
  1143. describe('commandLine.hasSwitch (existing argv)', () => {
  1144. it('returns true when present', async () => {
  1145. const { hasSwitch } = await runTestApp('command-line', '--foobar');
  1146. expect(hasSwitch).to.equal(true);
  1147. });
  1148. it('returns false when not present', async () => {
  1149. const { hasSwitch } = await runTestApp('command-line');
  1150. expect(hasSwitch).to.equal(false);
  1151. });
  1152. });
  1153. describe('commandLine.getSwitchValue', () => {
  1154. it('returns the value when present', () => {
  1155. app.commandLine.appendSwitch('foobar', 'æøåü');
  1156. expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
  1157. });
  1158. it('returns an empty string when present without value', () => {
  1159. app.commandLine.appendSwitch('foobar1');
  1160. expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
  1161. });
  1162. it('returns an empty string when not present', () => {
  1163. expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
  1164. });
  1165. });
  1166. describe('commandLine.getSwitchValue (existing argv)', () => {
  1167. it('returns the value when present', async () => {
  1168. const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
  1169. expect(getSwitchValue).to.equal('test');
  1170. });
  1171. it('returns an empty string when present without value', async () => {
  1172. const { getSwitchValue } = await runTestApp('command-line', '--foobar');
  1173. expect(getSwitchValue).to.equal('');
  1174. });
  1175. it('returns an empty string when not present', async () => {
  1176. const { getSwitchValue } = await runTestApp('command-line');
  1177. expect(getSwitchValue).to.equal('');
  1178. });
  1179. });
  1180. });
  1181. describe('default behavior', () => {
  1182. describe('application menu', () => {
  1183. it('creates the default menu if the app does not set it', async () => {
  1184. const result = await runTestApp('default-menu');
  1185. expect(result).to.equal(false);
  1186. });
  1187. it('does not create the default menu if the app sets a custom menu', async () => {
  1188. const result = await runTestApp('default-menu', '--custom-menu');
  1189. expect(result).to.equal(true);
  1190. });
  1191. it('does not create the default menu if the app sets a null menu', async () => {
  1192. const result = await runTestApp('default-menu', '--null-menu');
  1193. expect(result).to.equal(true);
  1194. });
  1195. });
  1196. describe('window-all-closed', () => {
  1197. it('quits when the app does not handle the event', async () => {
  1198. const result = await runTestApp('window-all-closed');
  1199. expect(result).to.equal(false);
  1200. });
  1201. it('does not quit when the app handles the event', async () => {
  1202. const result = await runTestApp('window-all-closed', '--handle-event');
  1203. expect(result).to.equal(true);
  1204. });
  1205. });
  1206. describe('user agent fallback', () => {
  1207. let initialValue: string;
  1208. before(() => {
  1209. initialValue = app.userAgentFallback!;
  1210. });
  1211. it('should have a reasonable default', () => {
  1212. expect(initialValue).to.include(`Electron/${process.versions.electron}`);
  1213. expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
  1214. });
  1215. it('should be overridable', () => {
  1216. app.userAgentFallback = 'test-agent/123';
  1217. expect(app.userAgentFallback).to.equal('test-agent/123');
  1218. });
  1219. it('should be restorable', () => {
  1220. app.userAgentFallback = 'test-agent/123';
  1221. app.userAgentFallback = '';
  1222. expect(app.userAgentFallback).to.equal(initialValue);
  1223. });
  1224. });
  1225. describe('app.allowRendererProcessReuse', () => {
  1226. it('should default to true', () => {
  1227. expect(app.allowRendererProcessReuse).to.equal(true);
  1228. });
  1229. it('should cause renderer processes to get new PIDs when false', async () => {
  1230. const output = await runTestApp('site-instance-overrides', 'false');
  1231. expect(output[0]).to.be.a('number').that.is.greaterThan(0);
  1232. expect(output[1]).to.be.a('number').that.is.greaterThan(0);
  1233. expect(output[0]).to.not.equal(output[1]);
  1234. });
  1235. it('should cause renderer processes to keep the same PID when true', async () => {
  1236. const output = await runTestApp('site-instance-overrides', 'true');
  1237. expect(output[0]).to.be.a('number').that.is.greaterThan(0);
  1238. expect(output[1]).to.be.a('number').that.is.greaterThan(0);
  1239. expect(output[0]).to.equal(output[1]);
  1240. });
  1241. });
  1242. describe('login event', () => {
  1243. afterEach(closeAllWindows);
  1244. let server: http.Server;
  1245. let serverUrl: string;
  1246. before((done) => {
  1247. server = http.createServer((request, response) => {
  1248. if (request.headers.authorization) {
  1249. return response.end('ok');
  1250. }
  1251. response
  1252. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1253. .end();
  1254. }).listen(0, '127.0.0.1', () => {
  1255. serverUrl = 'http://127.0.0.1:' + (server.address() as net.AddressInfo).port;
  1256. done();
  1257. });
  1258. });
  1259. it('should emit a login event on app when a WebContents hits a 401', async () => {
  1260. const w = new BrowserWindow({ show: false });
  1261. w.loadURL(serverUrl);
  1262. const [, webContents] = await emittedOnce(app, 'login');
  1263. expect(webContents).to.equal(w.webContents);
  1264. });
  1265. });
  1266. });
  1267. async function runTestApp (name: string, ...args: any[]) {
  1268. const appPath = path.join(fixturesPath, 'api', name);
  1269. const electronPath = process.execPath;
  1270. const appProcess = cp.spawn(electronPath, [appPath, ...args]);
  1271. let output = '';
  1272. appProcess.stdout.on('data', (data) => { output += data; });
  1273. await emittedOnce(appProcess.stdout, 'end');
  1274. return JSON.parse(output);
  1275. }