Electron is a great tool to create desktop applications.
Electron Basics
Electron consists of three parts: main process, renderer processes, and preload.
You only have one main process that is responsible for launching windows, controlling tray icons, and handling APIs that are only available for node, and not for web or Chrome.
The main process is a node process.
The preload lets us expose some node API to the renderer process.
The renderer process is attached to a Window, and it runs like JavaScript in the browser.
Testing both Main and Renderer code
The main code is a node code, and the renderer code is a browser code.
So we need a way to tell Jest to use different testing environments for each test.
There are two possible approaches to solving this
Using docblock
/**
* @jest-environment jsdom
*/
You can set the default test infra to use node, and in each renderer test file, you add this docblock to change the test environment.
The problem with this approach is that some developers can forget, and get some weird bugs hard to solve.
Using Jest Multi-Project-Runner
We can use Jest Multi-Project-Runner in a single repository, and modify each project to have their own configuration.
Let's see how to have 2 projects, one for main and another for renderer:
jest.config.js
module.exports = {
projects: [
'<rootDir>/jest.main.config.js',
'<rootDir>/jest.renderer.config.js',
],
}
jest.main.config.js
module.exports = {
testRegex: '((\\.|/)(main.spec))\\.(js|ts|tsx)?$',
testEnvironment: 'node',
}
jest.renderer.config.js
module.exports = {
testRegex: '((\\.|/)(renderer.spec))\\.(js|ts|tsx)?$',
testEnvironment: 'jsdom',
}
Using testRegex to match different testfiles we can turn the test environment explicit:
any *.main.spec.ts
will use node environment
any *.renderer.spec.ts
will use jsdom environment
Wrapping Up
You can use existing tools to adapt to your new use cases.
Jest multi-project runner is versatile and can also be used in a single repo to test different codes and requirements.
You can use the same approach to test nextjs backend, and frontend code, and also SSR and Server Components.
Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.
If you want to work with us, we are hiring!
Top comments (0)