h3poteto / electron-mock-ipc

Mock Electron's ipcMain, and ipcRenderer
MIT License
23 stars 6 forks source link

ipcMain.on doesn't listen for ipcRenderer.send calls #610

Open lucasrabiec opened 2 years ago

lucasrabiec commented 2 years ago

Hi, I configured the library in jest.config.js and mock's file as needed. I have the following code in my main process:

import { ipcMain } from 'electron';
...
export function someListener() {
  ipcMain.on('test-channel', () => {
    console.log('on test-channel');
    <some stuff which I'm mocking in tests to check if it is run>
  });
}

Then I run the following test:

import { ipcRenderer } from 'common/electron.mock';

test('run some stuff when test-channel event received', () => {
  someListener();
  ipcRenderer.send('test-channel');
  expect(mockedStuff).toHaveBeenCalled()
});

and nothing is called in ipcMain.on('test-channel') even console.log(). What am I doing wrong?

lucasrabiec commented 2 years ago

It looks like the solution is setting jest for main (node) and renderer (jsdom) separately via jest projects. Now I have different problem:

Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "on test-channel".

but I think it has nothing to do with this library.

h3poteto commented 2 years ago

Please show me your mock file. And did you replace electron module with the mock file?

lucasrabiec commented 2 years ago

Mock:

import { IpcMain, IpcRenderer } from 'electron';
import createIPCMock from 'electron-mock-ipc';

const mocked = createIPCMock();
const ipcMain = mocked.ipcMain as IpcMain;
const ipcRenderer = mocked.ipcRenderer as IpcRenderer;

export { ipcMain, ipcRenderer };

jest config:

moduleNameMapper: {
  ...pathsToModuleNameMapper(compilerOptions.paths),
  '^electron$': '<rootDir>/../common/electron.mock.ts',
},
h3poteto commented 2 years ago

It seems correct... Could you run the jest example code in your machine? https://github.com/h3poteto/electron-mock-ipc/tree/master/example/jest

lucasrabiec commented 2 years ago

Yes, all green.