Jest Testing Electron/React Component using window.require
I once faced this issue and below was what solved it for me:
I had to leverage on the module react-app-rewired
. this module Tweaks the webpack config(s), even for those using create-react-app(CRA)
without using 'eject' and without creating a fork of the react-scripts.
all you need is to add a config-overrides.js
file in the root of your project, and populate it with the snippet below:
module.exports = function override (config) {
config.target = 'electron-renderer'
return config;
}
then you proceed to your package.json
and replace your start script with
"start": "react-app-rewired start"
. and you are done. you can thereafter rebuild and run your test script without getting the window.require is not a function
error.
I hope I have been able to help.
cheers!
Add this line at the beginning of your test (or in a setupFilesAfterEnv
setup file):
window.require = require;
Details
electron
supplies window.require
but it isn't defined when running unit tests with Jest
.
By default Jest
provides a browser-like environment using jsdom
that includes a window
object.
The above line mocks window.require
by setting it equal to the current value of require
.