I'm currently creating an Electron application that uses React to create the interface. In order to get access the fs, I have been using:
const fs = window.require('fs');
Which works fine when in an Electron window.
The issue is that when I write jest tests for any components that use the window.require('fs'), I get the following error when running the test.
TypeError: window.require is not a function
I have looked through the documentation for Jest and it seems the solution is to generate a mock of window using a manual mock (see "Mocking methods which are not implemented in JSDOM" at https://jestjs.io/docs/en/manual-mocks). However, when I tried to mock window.require by adding at the top of my test file
window.require = jest.fn();
I still get the same TypeError.
I'm very new to create Jest mocks so any help with this would be much appreciated.
My current test file (Component.test.js) looks like
window.require = jest.fn();
import React from 'react';
import renderer from 'react-test-renderer';
import Component from '../index';
describe('Testing', () => {
it('Component renders correctly', () => {
const component = renderer.create(<Component />);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
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
.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With