hustcc / jest-electron

❯ ⚛️The easiest way to run and debug test cases in electron with jest.
https://github.com/hustcc/jest-electron
MIT License
154 stars 24 forks source link

Provide option to `enableRemoteModule` or configure any `webPreferences` #45

Open juanmartin opened 2 years ago

juanmartin commented 2 years ago

Hi! The project I'm currently working on needs to mock some remote.require we do on the angular side for some native modules we use.

import { remote } from 'electron';

/**
 * This mocks out main process modules that are incompatible with unit tests.
 */
const originalRequire = remote.require;
remote.require = jest.fn((moduleName) => {
  switch (moduleName) {
    // mock native module functions
    case './nativeModule':
      return () => true;
    // for all other modules, do not mock and return regular module
    default:
      return originalRequire(moduleName);
  }
});

Since the context in which Jest runs didn't include the needed enableRemoteModule: true web preference, as it's the default since Electron v10. Since we upgraded to v11, and still needed the remote module, our tests started failing. I ended up doing a manual override in the postinstall script of our project to manually replace the JestWorkerRPC.js file with a copy of it in which I added enableRemoteModule: true. Now our tests run and all is good. But I don't like to override a whole file within node_modules like this, so it would be nice to be able to configure certain aspects like the webPreferences of the BrowserWindow of the Jest Runner to avoid this kind of workaround.

I know the remote module is deprecated and it could be a security concern, but until we refactor our codebase, this is the solution we came up with.

Let me know if this is viable or anyone stumbled upon this case so that I can provide anything needed.

Thank you!

davidrichard23 commented 2 years ago

hey @juanmartin would you mind posting an example of your postinstall script?