api-ipc-main-spec.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { expect } from 'chai';
  2. import * as path from 'path';
  3. import * as cp from 'child_process';
  4. import { closeAllWindows } from './window-helpers';
  5. import { emittedOnce } from './events-helpers';
  6. import { defer } from './spec-helpers';
  7. import { ipcMain, BrowserWindow } from 'electron/main';
  8. describe('ipc main module', () => {
  9. const fixtures = path.join(__dirname, 'fixtures');
  10. afterEach(closeAllWindows);
  11. describe('ipc.sendSync', () => {
  12. afterEach(() => { ipcMain.removeAllListeners('send-sync-message'); });
  13. it('does not crash when reply is not sent and browser is destroyed', (done) => {
  14. const w = new BrowserWindow({
  15. show: false,
  16. webPreferences: {
  17. nodeIntegration: true
  18. }
  19. });
  20. ipcMain.once('send-sync-message', (event) => {
  21. event.returnValue = null;
  22. done();
  23. });
  24. w.loadFile(path.join(fixtures, 'api', 'send-sync-message.html'));
  25. });
  26. it('does not crash when reply is sent by multiple listeners', (done) => {
  27. const w = new BrowserWindow({
  28. show: false,
  29. webPreferences: {
  30. nodeIntegration: true
  31. }
  32. });
  33. ipcMain.on('send-sync-message', (event) => {
  34. event.returnValue = null;
  35. });
  36. ipcMain.on('send-sync-message', (event) => {
  37. event.returnValue = null;
  38. done();
  39. });
  40. w.loadFile(path.join(fixtures, 'api', 'send-sync-message.html'));
  41. });
  42. });
  43. describe('ipcMain.on', () => {
  44. it('is not used for internals', async () => {
  45. const appPath = path.join(fixtures, 'api', 'ipc-main-listeners');
  46. const electronPath = process.execPath;
  47. const appProcess = cp.spawn(electronPath, [appPath]);
  48. let output = '';
  49. appProcess.stdout.on('data', (data) => { output += data; });
  50. await emittedOnce(appProcess.stdout, 'end');
  51. output = JSON.parse(output);
  52. expect(output).to.deep.equal(['error']);
  53. });
  54. it('can be replied to', async () => {
  55. ipcMain.on('test-echo', (e, arg) => {
  56. e.reply('test-echo', arg);
  57. });
  58. defer(() => {
  59. ipcMain.removeAllListeners('test-echo');
  60. });
  61. const w = new BrowserWindow({
  62. show: false,
  63. webPreferences: {
  64. nodeIntegration: true
  65. }
  66. });
  67. w.loadURL('about:blank');
  68. const v = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  69. const { ipcRenderer } = require('electron')
  70. ipcRenderer.send('test-echo', 'hello')
  71. ipcRenderer.on('test-echo', (e, v) => {
  72. resolve(v)
  73. })
  74. })`);
  75. expect(v).to.equal('hello');
  76. });
  77. });
  78. });