ยท testing
Setup electron-mocha with @babel/register and TypeScript
This tutorial teaches you how to write tests for Electron using TypeScript and mocha. You'll learn about the necessary dependencies and how to set up your test environment.
Write tests for Electron using TypeScript and mocha. The following tutorial will show you how to create a test setup.
Contents
Environment
Tested with:
- Node.js v10.9.0
- Electron v4.0.5
Code files
{
"devDependencies": {
"@babel/core": "7.3.3",
"@babel/plugin-proposal-class-properties": "7.3.3",
"@babel/preset-env": "7.3.1",
"@babel/preset-typescript": "7.3.3",
"@babel/register": "7.0.0",
"@types/mocha": "5.2.6",
"electron": "4.0.5",
"electron-mocha": "6.0.4",
"typescript": "3.3.3"
},
"main": "dist/main.js",
"scripts": {
"test": "electron-mocha --require ./babel-register.js src/**/*.test.ts"
},
"version": "0.0.0"
}require('@babel/register')({
cache: false,
extensions: ['.ts'],
plugins: ['@babel/proposal-class-properties'],
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'@babel/preset-typescript',
],
});{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"outDir": "dist",
"rootDir": "src",
"target": "es5"
},
"exclude": ["dist", "node_modules"]
}Takeaways
Checklist
--require ./babel-register.jsmust be used because you need to specifyextensionsfor TypeScript and this cannot be done when using just--require @babel/register@babel/preset-envis required with anodetarget becauseelectron-mocharuns in a Node.js environment@babel/preset-typescriptis used to turn tests written in TypeScript into JavaScript: https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/- The
@babel/proposal-class-propertiesis optional and only required if you code makes already use of class properties
Good to know
- When your project contains a
babel.config.jsit may come to conflicts because@babel/registerwill pick it up and might overwrite settings defined inbabel-register.js: https://babeljs.io/docs/en/babel-register#specifying-options - Since Mocha 4 the
--compilersflag is deprecated and got replaced by--require: https://babeljs.io/docs/en/next/tools/mocha/usage
