electron-react-boilerplate icon indicating copy to clipboard operation
electron-react-boilerplate copied to clipboard

Jest cannot read properties of undefined (reading 'ipcRenderer')

Open rossicler-hostalky opened this issue 3 years ago • 4 comments

Summary

I'm trying to fix an issue with tests that are returning the following error:

Jest cannot read properties of undefined (reading 'ipcRenderer')

export const mainBridge = window.electron.ipcRenderer;

I added this exported const to use across my renderer process, instead of using the window object directly. I assumed that jest can't read the window object of an browser, so I tried mocking this const, but it didn't work. This is my test code:

// App.test.tsx

import '@testing-library/jest-dom';
import { render } from '@testing-library/react';
import App from '../renderer/App';

jest.mock('../renderer/utils/helpers', () => {
  const originalModule = jest.requireActual('../renderer/utils/helpers');
  return {
    __esModule: true,
    ...originalModule,
    mainBridge: {
      sendMessage: (): void => {
        // do nothing
      },
      invokeMessage() {
        return {};
      },
      on() {
        // do nothing
      },
      onReduxDispatch() {
        // do nothing
      },
      once() {
        // do nothing
      },
    },
  };
});

describe('App', () => {
  it('should render', () => {
    expect(render(<App />)).toBeTruthy();
  });
});

My question is, how can I fix this issue? Should I use something like electron-mocha instead of jest?

I would really appreciate If someone could help me with this. Thanks for the wonderful boilerplate you guys created.

rossicler-hostalky avatar Apr 13 '23 20:04 rossicler-hostalky

+1

lczhai avatar Aug 30 '23 07:08 lczhai

@rossicler-hostalky Did find the solution for this issue?

rajrkrish avatar Dec 10 '23 13:12 rajrkrish

have the same issue

protogrammer avatar Dec 10 '23 19:12 protogrammer

Try this

// This is how it is defined in the context bridge in my code. Modify this as required
const mockElectron = {
  ipcRenderer: {
    sendMessage: jest.fn(),
    on: jest.fn(),
    once: jest.fn(),
    removeEventListener: jest.fn(),
  },
};
 beforeAll(() => {
    global.window.electron = mockElectron;
 });

rajrkrish avatar Dec 11 '23 13:12 rajrkrish