Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron + Jest - ipcRenderer is undefined in unit tests

I am contributing to a project which is built with React (with webpack) running in Electron. When executing unit tests with Jest, it fails with the error TypeError: Cannot read property 'on' of undefined (and works fine when not testing, eg. run with Electron).

The code:

import React, { Component } from 'react';
import { ipcRenderer } from  'electron';
// some more imports

class Setup extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // some state
    };

    ipcRenderer.on('open-file-reply', this.someMethod); // << fails on this line
  }
  // more class stuff
}
like image 249
Technotronic Avatar asked Dec 02 '22 12:12

Technotronic


2 Answers

It took me a few days but finally, I found this answer in this great blog post. Quote:

Jest is called from Node and doesn't run test code through Webpack. Instead, we have to use Jest's mocking functions to replace the import with a stub file.

Jest has a helper method called moduleNameMapper [object<string, string>] . From jest documentation:

A map from regular expressions to module names that allow to stub out resources, like images or styles with a single module.

It should be added in your package.json root object like this:

{
  "name": "My awesome app",
  "jest": {
    "moduleNameMapper": {
      "electron": "<rootDir>/src/components/tests/mock/electron.js"
    }
  }
}

and the mock file itself (/src/components/tests/mock/electron.js):

export const ipcRenderer = {
  on: jest.fn()
};

This way you can stub other electron modules and methods (like remote which is shown in the blog above).

like image 130
Technotronic Avatar answered Jan 03 '23 10:01

Technotronic


Another way is creating an electron.js file in __mocks__ in your root folder.

The electron.js should look something like

export const ipcRenderer = {
  on: jest.fn(),
};

You can read more at https://jestjs.io/docs/en/manual-mocks#mocking-node-modules

like image 38
kontrollanten Avatar answered Jan 03 '23 09:01

kontrollanten